How to pass arguments to a Button command in Tkinter?

前端 未结 18 2829
夕颜
夕颜 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条回答
  •  旧时难觅i
    2020-11-21 08:04

    Just to make the answer of Nae a little bit more elaborate, here is a full blown example which includes the possibility to pass a variable to the callback which contains different values for each button:

    import tkinter as tk
        
    def callback(text):
        print(text)
    
    top = tk.Tk()
    Texts=["text1", "text2", "text3"]
    Buttons=[]
    
    for i, z in enumerate(Texts):
        Buttons.append(tk.Button(top, text=z, command= lambda ztemp=z : callback(ztemp)))
        Buttons[i].pack(side=tk.LEFT, padx=5)
    
    top.mainloop()
    

    By defining a temporary variable ztemp, the value of that variable gets fixed at the moment when the button is defined.

提交回复
热议问题