button command option in tkinter

我的梦境 提交于 2020-02-04 10:49:08

问题


In the little GUI app below. When I use button's command option to call a function. It doesn't work like this: self.update() rather it works like this: self.update. Why so? Is is some special way that command option of a button works? I think a method or a function should be called with those braces (), unless it's a property:

i.e.

     @name.setter:
     def setter(self, name): 
             self.name = name

     #main 
     object.name = "New_obj"

Note: The above is just a template so you might get my point. I didn't write the complete valid code. Including class and everything.

from tkinter import *

class MuchMore(Frame):
    def __init__(self, master):
        super(MuchMore,self).__init__(master)
        self.count =0 
        self.grid()
        self.widgets()

    def widgets(self):
        self.bttn1 = Button(self, text = "OK")
        self.bttn1.configure(text = "Total clicks: 0")
        self.bttn1["command"] = self.update    # This is what I am taking about 
        self.bttn1.grid() 

    def update(self):
        self.count += 1
        self.bttn1["text"] = "Total clicks" + str(self.count)


#main

root = Tk()
root.title("Much More")
root.geometry("324x454")
app = MuchMore(root)

回答1:


It is a high order function, meaning you are referencing a function as an object. You are not calling the function and assigning the command to the return value of the function. See here for more information.




回答2:


The command parameter takes a reference to a function -- ie: the name of the function. If you add parenthesis, you're asking python to execute the function and give the result of the function to the command parameter.



来源:https://stackoverflow.com/questions/28773731/button-command-option-in-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!