How to pass arguments to a Button command in Tkinter?

前端 未结 18 3223
夕颜
夕颜 2020-11-21 07:42

Suppose I have the following Button made with Tkinter in Python:

import Tkinter as Tk
win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=         


        
18条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 08:11

    Building on Matt Thompsons answer : a class can be made callable so it can be used instead of a function:

    import tkinter as tk
    
    class Callback:
        def __init__(self, func, *args, **kwargs):
            self.func = func
            self.args = args
            self.kwargs = kwargs
        def __call__(self):
            self.func(*self.args, **self.kwargs)
    
    def default_callback(t):
        print("Button '{}' pressed.".format(t))
    
    root = tk.Tk()
    
    buttons = ["A", "B", "C"]
    
    for i, b in enumerate(buttons):
        tk.Button(root, text=b, command=Callback(default_callback, b)).grid(row=i, column=0)
    
    tk.mainloop()
    

提交回复
热议问题