Tkinter之一(TCL/Tk在Python上的移植)

What is Tkinter?

 TkinterPythonGUI widget。它是基于Tk工具包的,而Tk最初是为了工具命令语言(Tool Command Language, TCL)设计的。由于Tk的流行,它被移植到Perl(Perl/Tk)Python(Tkinter)

A minimal application

#!/usr/bin/python
from Tkinter import 
*

class Application(Frame):                           
         def __init__(self, master 
= None):
Frame.__init__(self, master)
self.grid()
self.createWidget()
          
          def createWidgets(self):
                self.quitButton 
= Button(self, text = ‘Quit’, command=self.quit)
                self.quitButton.grid()
app 
= Application()
app.master.title(‘Sample application’)
app.mainloop()

 

注意:Application类必须从Frame类继承而来,其__init__函数宜先调用其父类的__init__。其中grid()函数用于将Widget显示出来,感觉应该是跟组件的pack()类似。

另外一种形式的Hello, world

#title: HelloWorld.py
from Tkinter import 
*

root 
= Tk()
label 
= Label(text = “hello world”);
label.pack()

root.mainloop()

Layout management

尽管在Tkinter中有三种geometry managers,但是本文将使用.grid()。这种Layout管理器将所有的widget都看成是一个由列跟行组成的表格。通常包含如下术语:

 

  • 单元cell
  • 宽width
  • 高 height
  • extra space
  • 合并单元格spanning

创建了一个widget后,只有将其向geometry manager注册后,该widget才会显示出来。

thing = Constructor(master, …)
thing.grid(…)

用类封装的Hello, world例子。

#file : hello2.py

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()

        def say_hi(self):
            print ‘hi there, everyone
!

root 
= Tk()
app 
= App(root)
root.mainloop()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章