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

これは関数呼び出しではなく、辞書内の参照ストレージです。

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

ほとんどの場合、Buttonオブジェクトには、特定の対話時にこのメソッドを呼び出す機能があります。

于 2013-01-09T09:47:41.370 に答える
0

そのメソッドからは呼び出されません。これは、関数への参照を使用しています。この関数は、後でボタンがクリックされたときに呼び出されます。これは、関数の名前がその関数のコードへの参照であると考えることができます。関数を呼び出すには、()演算子を適用します。

于 2013-01-09T09:46:56.070 に答える