Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

python - Passing *args through a tkinter bind function?

I have a lot of buttons and I use images in them so I created a class to make it readable but I have a problem because I have sometimes a multiple arguments functions (to use it in the bind section below).

This is my code:

class myButton():

  def __init__(self, master, relx: float, rely: float, relwidth: float, relheight: float, color, image, function, *args):
    self.master = master
    self.relx = relx
    self.rely = rely
    self.relwidth = relwidth
    self.relheight = relheight
    self.color = color
    self.image = image
    self.function = function

    self.myButton = Button(master, bg=self.color, image=self.image, activebackground=self.color, bd=0)
    self.myButton.place(relx=self.relx, rely=self.rely, relheight=self.relheight, relwidth=self.relwidth)
    # The problem is in the following line
    self.myButton.bind("<Button-1>", lambda event, *args: self.function(event, *args))

  def place_forget(self):
    self.myButton.place_forget()

  def show(self):
    self.myButton.place(relx=self.relx, rely=self.rely, relheight=self.relheight, relwidth=self.relwidth)

Do you have any suggestions?

When I pass argument in the place of *args I get an error that arguments are missing

Exemples of Entries

First with error

buttonname1 = myButton(master1, 0.75, 0.5, 0.25, 0.25, color_main_content, ButtonValidate,
                                       function, argument1, argument1)

function1 is multivariable function

ButtonValidate is an image

argument1 and argument2 (maybe more arguments for other functions)

definition of the function

def function(event, argument1, argument2):
    pass # main function

Example without multiple arguments

buttonname2 = myButton(master2, 0.75, 0.5, 0.25, 0.25, color_main_content, ButtonNext,
                                       function1)

definition of function 2

def function2(event):
   pass

I want a class that works for both situations

Error Message:

TypeError: function() missing 2 required positional arguments: 'argument1' and 'argument2'

question from:https://stackoverflow.com/questions/65853785/passing-args-through-a-tkinter-bind-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...