3

我知道这是一个菜鸟问题,但我试图弄清楚为什么“self.update_count”在从“create_widget”方法调用时不需要括号。我一直在寻找,但找不到原因。

请帮忙。

# Click Counter
# Demonstrates binding an event with an event handler

from Tkinter import *

class Skeleton(Frame):
   """ GUI application which counts button clicks. """
   def __init__(self, master):
       """ Initialize the frame. """
       Frame.__init__(self, master)
       self.grid()
       self.bttn_clicks = 0 # the number of button clicks
       self.create_widget()

   def create_widget(self):
       """ Create button which displays number of clicks. """
       self.bttn = Button(self)
       self.bttn["text"] = "Total Clicks: 0"
       # the command option invokes the method update_count() on click
       self.bttn["command"] = self.update_count
       self.bttn.grid()

   def update_count(self):
       """ Increase click count and display new total. """
       self.bttn_clicks += 1
       self.bttn["text"] = "Total Clicks: "+ str(self.bttn_clicks)

# main root = Tk() root.title("Click Counter") root.geometry("200x50")

app = Skeleton(root)

root.mainloop()
4

3 回答 3

2
self.update_count()

将是对该方法的调用,所以

self.bttn["command"] = self.update_count()

将方法的结果存储在self.bttn. 然而,

self.bttn["command"] = self.update_count

没有括号将方法本身存储在self.bttn. 在 Python 中,方法和函数是可以传递、存储在变量中等的对象。

作为一个简单的例子,考虑以下程序:

def print_decimal(n):
    print(n)

def print_hex(n):
    print(hex(n))

# in Python 2.x, use raw_input
hex_output_wanted = input("do you want hex output? ")

if hex_output_wanted.lower() in ('y', 'yes'):
    printint = print_hex
else:
    printint = print_decimal

# the variable printint now holds a function that can be used to print an integer
printint(42)
于 2013-01-09T09:45:28.783 回答
1

This is not a function call but a reference storage inside a dictionary:

self.bttn["command"] = self.update_count 
// stores reference to update_count inside self.bttn["command"]
// invokable by self.bttn["command"]()

Most probably the Button object has the capability of calling this method upon certain interaction.

于 2013-01-09T09:47:41.370 回答
0

它不是从该方法调用的。它使用对函数的引用,该按钮稍后会在单击时调用该函数。您可以将其视为一个函数的名称,它是对该函数中代码的引用;调用您应用 () 运算符的函数。

于 2013-01-09T09:46:56.070 回答