Hello, Again
When you write larger programs, it is usually a good idea to wrap your code up in one or more classes. The following example is adapted from the “hello world”program in Matt Conway’s A Tkinter Life Preserver (dead link).
當編寫大型應用的時候把程式碼封裝裹成一個或多個類是個不錯的注意。下面這個例子改編自Matt Conway的 A Tkinter Life Preserver (死連結)中的“hello world”。 Our Second Tkinter Program
from Tkinter import *class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button( frame, text="QUIT", fg="red", command=frame.quit ) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!"root = Tk()app = App(root)root.mainloop()root.destroy() # optional; see description below
Running the Example
When you run this example, the following window appears.
運行這個程式,將會出現下面的視窗 Running the sample program (using Tk 8.0 on a Windows 95 box)
If you click the right button, the text “hi there, everyone!” is printed to the console. If you click the left button, the program stops.
如果點擊右邊的按鈕,將會在console裡面列印"hi there, everyone!"。如果點擊左邊的按鈕,程式將會停止。
Note: Some Python development environments have problems running Tkinter examples like this one. The problem is usually that the enviroment uses Tkinter itself, and the mainloop call and the quit calls interact with the environment’s expectations. Other environments may misbehave if you leave out the explicit destroy call. If the example doesn’t behave as expected, check for Tkinter-specific documentation for your development environment.
注意:一些Python開發環境在運行類似上面這個Tkinter例子的時候會出現問題。這個問題通常是環境在使用Tkinter本身,調用mainloop和quit的時候會影響到環境預期。如果遺漏掉明確調用destroy的話其他環境會產生行為異常。如果這個例子沒有期望的行為,那麼檢查一下開發環境的Tkinter-specific文檔。 Details
This sample application is written as a class. The constructor (the __init__method) is called with a parent widget (the master), to which it adds a number of child widgets. The constructor starts by creating a Frame widget. A frame is a simple container, and is in this case only used to hold the other two widgets.
這個樣本應用被寫作一個類。這個構造器(__init__方法)被一個父組件(master)調用。構造器以建立一個Frame組件開始。這個架構是一個簡單的容器,它是用來容納其他兩個組件的。
class App: def __init__(self, master): frame = Frame(master) frame.pack()
The frame instance is stored in a local variable called frame. After creating the widget, we immediately call the pack method to make the frame visible.
這個frame執行個體被儲存在一個成文frame的本地變數裡面。在建立完成以後,馬上可以調用pack方法去讓frame變得可視。
We then create two Button widgets, as children to the frame.
建立兩個Button組件作為frame的孩子。
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)self.button.pack(side=LEFT)self.hi_there = Button(frame, text="Hello", command=self.say_hi)self.hi_there.pack(side=LEFT)
This time, we pass a number of
options to the constructor, as keyword arguments. The first button is labelled “QUIT”, and is made red (
fg is short for
foreground). The second is labelled “Hello”. Both buttons also take a
command option. This option specifies a function, or (as in this case) a bound method, which will be called when the button is clicked.
這次傳遞了一些選項給這個構造作為關鍵參數。第一個按鈕被標記為"QUIT",並被標為紅色(fg是foreground的縮寫)。第二個被標記為"Hello".倆個按鈕都有一個command選項,這個選項指派一個函數或者一個綁定的方法,它們會在按鈕被點擊的時候被調用。
The button instances are stored in instance attributes. They are both packed, but this time with the side=LEFT argument. This means that they will be placed as far left as possible in the frame; the first button is placed at the frame’s left edge, and the second is placed just to the right of the first one (at the left edge of the remaining space in the frame, that is). By default, widgets are packed relative to their parent (which is master for the frame widget, and the frame itself for the buttons). If the side is not given, it defaults to TOP.
按鈕執行個體被儲存在執行個體屬性中。它們都被打包,帶有一個參數side=LEFT。這就意味著它們被放置在架構的最左側。第一個按鈕被放置在架構的最左邊,第二個按鈕緊靠第一個按鈕的右邊(這是架構剩餘空間的最左邊)。一般來說,組件打包和父組件有關(對於架構組件來說是master,而對於按鈕來說是架構本身)。如果side參數沒有被給定,預設值是TOP。
The “hello” button callback is given next. It simply prints a message to the console everytime the button is pressed:
接下來指派"hello"按鈕的回呼函數。它在按鈕被按下的時候簡單的在console中列印一條資訊。
def say_hi(self): print "hi there,everypne !"
Finally, we provide some script level code that creates a
Tk root widget, and one instance of the
App class using the root widget as its parent:
最後,提供一些指令碼層面的代碼建立一個Tk根組件和一個使用根組件作為父組件的App類執行個體
root = Tk()app = App(root)root.mainloop()root.destory()
The
mainloop call enters the Tk event loop, in which the application will stay until the
quit method is called (just click the QUIT button), or the window is closed.
mainloop調用進入Tk事件迴圈,直到quit方法被調用(只要點擊QUIT按鈕)或者視窗被關閉之前應用都會呆在事件迴圈裡。
The destroy call is only required if you run this example under certain development environments; it explicitly destroys the main window when the event loop is terminated. Some development environments won’t terminate the Python process unless this is done.
只有當在特定的開發環境中運行這個例子的時候才需要調用destroy方法。當事件迴圈結束的是它會明確的銷毀主視窗。如果不這樣做的話一些開發環境不會結束Python進程。 More on widget references
In the second example, the frame widget is stored in a local variable named frame, while the button widgets are stored in two instance attributes. Isn’t there a serious problem hidden in here: what happens when the __init__ function returns and the frame variable goes out of scope?
在第二個例子中,frame組件儲存在一個名字為frame的本地變數中,而按鈕組件儲存在兩個執行個體屬性中。這是不是隱藏了一個嚴重的問題“當__init__函數返回和frame變數超出範圍以後會發生什麼。
Just relax; there’s actually no need to keep a reference to the widget instance. Tkinter automatically maintains a widget tree (via the master and children attributes of each widget instance), so a widget won’t disappear when the application’s last reference goes away; it must be explicitly destroyed before this happens (using the destroy method). But if you wish to do something with the widget after it has been created, you better keep a reference to the widget instance yourself.
放鬆些,事實上不需要對保持參考組件執行個體保持一個參考。Tkinter會自動地維護一個組件樹(通過每一個組件執行個體的master和children屬性),所以在應用的最後一個參考離開之前這個組件不會消失,必須顯示的去銷毀才行(使用destroy方法)。但如果想在一個組件被建立後對它做些什麼,最好是自己對組件執行個體保持參考。
Note that if you don’t need to keep a reference to a widget, it might be tempting to create and pack it on a single line:
注意如果不需要對一個組件保持參考,那麼可以通過一行嘗試建立和pack它。
Button(frame, text="hello", command=self.hello).pack(side=LEFT)
Don’t store the result from this operation; you’ll only get disappointed when you try to use that value (the
pack method returns
None). To be on the safe side, it might be better to always separate construction from packing:
不要儲存這個操作的傳回值,當這樣做的時候會很失望(pack方法返回None)。安全起見,最好是分開來構造。
w = Button(frame, text = "Hello", command = self.hello)w.pack(side=LEFT)
More on widget names
Another source of confusion, especially for those who have some experience of programming Tk using Tcl, is Tkinter’s notion of the widget name. In Tcl, you must explicitly name each widget. For example, the following Tcl command creates a Button named “ok”, as a child to a widget named “dialog” (which in turn is a child of the root window, “.”).
另外一個困惑,尤其對於有使用Tcl對Tk編程經驗的人,是Tkinter的組件名稱概念。在Tck中,你必須顯式的命名每一個組件,例如下面的Tcl命令建立一個名為"Ok"的按鈕作為名為"dialog"的組件的孩子。
button.dialog.ok
The corresponding Tkinter call would look like:
正確的Tkinter調用應該是這樣:
ok = Button(dialog)
However, in the Tkinter case, ok and dialog are references to widget instances, not the actual names of the widgets. Since Tk itself needs the names, Tkinter automatically assigns a unique name to each new widget. In the above case, the dialog name is probably something like “.1428748,” and the button could be named “.1428748.1432920”. If you wish to get the full name of a Tkinter widget, simply use the str function on the widget instance:
總之,在Tkinter例子中,Ok和dialog是組件執行個體的參考,而非真正的名字。因為Tk本身需要名字,Tkinter自動地為每一個新組件分配一個獨一無二的名字。在上面的例子中,dialog名字可能是想".1428748"的東西,按鈕可能是".128748.1432920"。如果想得到一個Tkinter組件的全名,可以使用組件執行個體的str函數:
>>>print str(ok)1428748.1432920
(if you print something, Python automatically uses the str function to find out what to print. But obviously, an operation like “name = ok” won’t do the that, so make sure always to explicitly use str if you need the name).
(如果想列印些什麼,Python自動地使用str函數去找到要列印什麼。但是顯然像"name = ok"這樣的一個操作不會這樣做,所以當需要獲得名字的時候要顯式的使用str)
If you really need to specify the name of a widget, you can use the name option when you create the widget. One (and most likely the only) reason for this is if you need to interface with code written in Tcl.
如果需要為一個組件指定名字,可以在建立組件的時候使用name選項。這樣做的原因可能是你需要Tcl代碼的介面。
In the following example, the resulting widget is named “.dialog.ok” (or, if you forgot to name the dialog, something like “.1428748.ok”):
在下面的例子中,結果就是這個組件被命名為".dialog.ok"(或者是一個想".1428748"的東西,如果你忘記命名這個會話的話)
ok = Button(dialog, name = 'ok')
To avoid conflicts with Tkinter’s naming scheme, don’t use names which only contain digits. Also note that
name is a “creation only” option; you cannot change the name once you’ve created the widget.
為了避免和Tkinter明明規範衝突,是要使用全是數位名字。注意選項name是一個"creation only"選項,一旦建立好組件就不能再更改它的名字。