0%

Python Tkinter 你好2

你好,Tkinter2

如果程序写的大了,一般需要把代码包装到一个或许多类里面。

第二个Hello程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/python
#tk/helloworld_class.py
# -*- coding: UTF-8 -*-

from tkinter import *

class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()

self.button = Button(frame, text='Quit', foreground='red', background='blue', 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, welcome to tkinter!')

root = Tk()

app = App(root)

root.mainloop()
root.destroy() # optional; see description below

运行程序

运行这个程序,将会出现下面的这个窗口。

Hello

点击Hello按钮,终端输出信息 “Hi there, welcome to tkinter!”,如果点击Quit按钮,程序将退出。

注意:有些程序可能不会按照上面介绍的运行,这个时候就要检查下Tkinter的说明文档了,看看操作环境相关的配置,然后debug。

细节

这个示例,我们使用了class方法。初始化init方法创建一个继承自master的容器frame

1
2
3
4
5
class App:

def init(self, master):
frame = Frame(master)
frame.pack()

frame实例存储为局部变量,创建这个组建后,调用pack方法使之可见。

然后创建2个按钮组件,为frame的子组件。

1
2
3
4
5
self.button = Button(frame, text='Quit', foreground='red', background='blue', 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)

这次,我们传递了一定数量的选项给结构器,第一个按钮被标记为 “QUIT”,前景色为红色 (其中fg 是foreground的简称)。第二个标记为 “Hello”。两个按钮都有一个command选项,这个选项指定了一个函数或者方法,在按钮被点击的时候调用。

按钮实例存储在实例属性组中。side=LEFT 参数表示这两个按钮在帧中将被分开放置;第一个按钮被放置
在帧的左边缘,第二个被放在第一个的右边(帧的左边缘仍保留着空格)。默认情况下,部件的放置都是相对
于它们的父亲(frame 部件相对于 masterbutton 相对于 frame)。如果 side 选项没指定,side 默认
值为 TOP

“hello” 按钮的回调函数如下所示,每次点击的时候都会在终端打印一条消息:

1
2
def say_hi(self):
print('Hi there, welcome to tkinter!')

最后,我们使用一些脚本来创建 Tk root 部件和一个App的实例(使用root作为它的父类):

1
2
3
4
5
6
root = Tk()

app = App(root)

root.mainloop()
root.destroy()

关于部件引用

1
Button(frame, text="Hello", command=self.hello).pack(side=LEFT)

如果不需要对一个窗口部件进行引用,可以用单独的一行创建并且进行包装,如上所述。

但是如果需要对其进行调用,就需要分开了,如下所示:

1
2
w = Button(frame, text="Hello", command=self.hello)
w.pack(side=LEFT)

关于部件名字

在上述实例中,我们使用的button或者hi_there都是部件的引用,而不是部件实际的名字,实际的名字大部分是由一系列数字组成的,这个有Tkinter自动为这些新部件赋值。

比如,我们可以打印出来名字如下所示:

1
2
>>> print str(ok)
.1428748.1432920
处无为之事,行不言之教;作而弗始,生而弗有,为而弗恃,功成不居!

欢迎关注我的其它发布渠道