代码之家  ›  专栏  ›  技术社区  ›  Rikg09

按钮不工作的Tkinter命令[重复]

  •  2
  • Rikg09  · 技术社区  · 7 年前

    from Tkinter import *
    
    class App:
    
        def __init__(self, root):
            self.title = Label(root, text="Choose a food: ",
                               justify = LEFT, padx = 20).pack()
            self.label = Label(root, text = "Please select a food.")
            self.label.pack()
    
            self.var = StringVar()
            self.var.set("Apple")
            food = ["Apple", "Banana", "Pear"]
            option = apply(OptionMenu, (root, self.var) + tuple(food))
            option.pack()
    
            button = Button(root, text = "Choose", command=self.select())
            button.pack()
    
        def select(self):
            selection = "You selected the food: " + self.var.get()
            print(self.var.get()) #debug message
            self.label.config(text = selection)
    
    if __name__ == '__main__':
        root = Tk()
        app = App(root)
        root.mainloop()
    

    我是Tkinter的初学者,在制作我的完整应用程序之前,我正在努力弄清楚基本知识。提前感谢:)

    3 回复  |  直到 7 年前
        1
  •  9
  •   Noshii    7 年前

    button = Button(root, text = "Choose", command=self.select()) button = Button(root, text = "Choose", command=self.select) . 注意self后面删除的括号。选择这样,该方法只会被引用,直到您按下按钮才实际执行。

        2
  •  2
  •   asongtoruin    7 年前

    command=self.food() :

    button = Button(root, text="Choose", command=self.select)
    

    作为旁注,您生成 OptionMenu

    option = OptionMenu(root, self.var, *food)
    
        3
  •  0
  •   mayure098    7 年前

    enter image description here tkinterbook .

    (按下按钮时调用的函数或方法。回调可以是函数、绑定方法或任何其他可调用的Python对象。如果不使用此选项,则用户按下按钮时不会发生任何事情。)

    from Tkinter import *
    
    class App:
    
        def __init__(self, root):
            self.title = Label(root, text="Choose a food: ",
                               justify = LEFT, padx = 20).pack()
            self.label = Label(root, text = "Please select a food.")
            self.label.pack()
    
            self.var = StringVar()
            self.var.set("Apple")
            food = ["Apple", "Banana", "Pear"]
            option = apply(OptionMenu, (root, self.var) + tuple(food))
            option.pack()
    
            button = Button(root, text = "Choose", command=self.select)
            #use function name instead of aclling the function
            button.pack()
    
        def select(self):
            selection = "You selected the food: " + self.var.get()
            print(selection) #debug message
            self.label.config(text = selection)
    
    if __name__ == '__main__':
        root = Tk()
        app = App(root)
        root.mainloop()