Python GUI programming(tkinter)
python3之前的版本用Tkinter,之后用的是tkinter
最简单的使用Tkinter的代码,首先要Tk()建立一个窗口,然后加进各种Widget
from Tkinter import * window = Tk() label = Label(window, text = "Welcome to Python") button = Button(window, text = "Click me") label.pack() button.pack() window.mainloop()
Tkinter编程是基于事件驱动型的,当点击一个按键时,可以通过一个函数处理这个事件
from Tkinter import * def processOK(): print("OK") def processCancel(): print("Cancel") window = Tk() btOK = Button(window, text = "OK", fg = "red", command = processOK) btCancel = Button(window, text = "Cancel", bg = "yellow", command = processCancel) btOK.pack() btCancel.pack() window.mainloop()
其中参数command就是绑定的函数
还有各种可用的Widget Classes
- Button
- Canvas
- Checkbutton
- Entry
- Frame
- Label
- Menu
- Menubutton
- Message
- Radiobutton
- Text
可以直接修改widget的某项属性:
btShowOrHide = Button(window, text = "Show", bg = "white") btShowOrHide["text"] = "Hide" btShowOrHide["bg"] = "red" btShowOrHide["fg"] = "#AB84F9" # Change fg color to #AB84F9 btShowOrHide["cursor"] = "plus" # Change mouse cursor to plus btShowOrHide["justify"] = LEFT # Set justify to LEFT
IntVar(), StringVar()
from Tkinter import * class WidgetsDemo: def __init__(self): window = Tk() window.title('Widgets Demo') frame1 = Frame(window) frame1.pack() self.v1 = IntVar() self.v2 = IntVar() rbRed = Radiobutton(frame1, text = "Red", bg = "red", variable = self.v2, value = 1, command = self.processRadiobutton) rbYellow = Radiobutton(frame1, text = "Yellow", bg = "yellow", variable = self.v2, value = 2, command = self.processRadiobutton) rbRed.grid(row = 1, column = 2) rbYellow.grid(row = 1, column = 3) frame2 = Frame(window) frame2.pack() label = Label(frame2, text = "Enter your name : ") self.name = StringVar() entryName = Entry(frame2, textvariable = self.name) btGetName = Button(frame2, text = "get name", command = self.processButton) message = Message(frame2, text = "it is a widgets demo") label.grid(row = 1, column = 1) entryName.grid(row = 1, column = 2) btGetName.grid(row = 1, column = 3) message.grid(row = 1, column = 4) window.mainloop() def processRadiobutton(self): print(("Red" if self.v2.get() == 1 else "Yellow") + " is selected") def processButton(self): print("Your name is " + self.name.get()) WidgetsDemo()
上面代码中两种颜色的按键与IntVar()类型变量绑定,分别赋值1和2,然后可以用get()得到IntVar()的值,而输入文本窗口则绑定字符串变量StringVar()
Canvas: 可以用来展示一些图形
from Tkinter import * class CanvasDemo: def __init__(self): window = Tk() window.title("canvas demo") self.canvas = Canvas(window, width = 200, height = 100, bg = "white") self.canvas.pack() frame = Frame(window) frame.pack() btRectangle = Button(frame, text = "tectangle", command = self.displayRect) btRectangle.grid(row = 1, column = 1) window.mainloop() def displayRect(self): self.canvas.create_rectangle(10, 10, 190, 90, tags = "rect") CanvasDemo()
Menus
menubar = Menu(window) window.config(menu = menubar) # Display the menu bar operationMenu = Menu(menubar, tearoff = 0) menubar.add_cascade(label = "Operation", menu = operationMenu) # 菜单头 operationMenu.add_command(label = "Add", command = self.add) operationMenu.add_command(...) # 增加菜单选项 exitmenu = Menu(menubar, tearoff = 0) menubar.add_cascade(label = "Exit", menu = exitmenu) exitmenu.add_command(label = "Quit", command = window.quit)
Popup Menus
from Tkinter import * class PopupMenuDemo: def __init__(self): window = Tk() window.title("popup menu demo") self.menu = Menu(window, tearoff = 0) self.menu.add_command(label = "draw a line", command = self.displayLine) self.menu.add_command(label = "draw an oval", command = ...) def displayLine(self): ...
Mouse, Key events, and Bindings
widget.bind(event, handler)
def popup(event): menu.post(event.x_root,event.y_root)
Event | Description |
---|---|
<Bi-Motion> | An event occurs when a mouse button is moved while being held down on the widget. |
<Button-i> | Button-1, Button-2, and Button-3 identify the left, middle, and right buttons. When a mouse button is pressed over the widget, Tkinter automatically grabs the mouse pointer’s location. ButtonPressed-i is synonymous with Button-i. |
<ButtonReleased-i> | An event occurs when a mouse button is released. |
<Double-Button-i> | An event occurs when a mouse button is double-clicked. |
<Enter> | An event occurs when a mouse pointer enters the widget. |
<Key> | An event occurs when a key is pressed. |
<Leave> | An event occurs when a mouse pointer leaves the widget. |
<Return> | An event occurs when the Enter key is pressed. You can bind any key such as A, B, Up, Down, Left, Right in the keyboard with an event. |
<Shift+A> | An event occurs when the Shift+A keys are pressed. You can combine Alt, Shift, and Control with other keys. |
<Triple-Button-i> | An event occurs when a mouse button is triple-clicked. |
Event Properties
Event Properties | Description |
---|---|
char | The character entered from the keyboard for key events. |
keycode | The key code (i.e., Unicode) for the key entered from the keyboard for key events. |
keysym | The key symbol (i.e., character) for the key entered from the keyboard for key events. |
num | The button number (1, 2, 3) indicates which mouse button was clicked. |
widget | The widget object that fires this event. |
x and y | The current mouse location in the widget in pixels. |
x_ root and y_root | The current mouse position relative to the upper-left corner of the screen, in pixels. |
from Tkinter import * class MouseKeyEventDemo: def __init__(self): window = Tk() window.title("event demo") canvas = Canvas(window, bg = "white", width = 200, height = 100) canvas.pack() # Bind with <Button-1> event canvas.bind("<Button-1>", self.processMouseEvent) # Bind with <Key> event canvas.bind("<Key>", self.processKeyEvent) canvas.focus_set() # 对该窗口设置键盘焦点 window.mainloop() def processMouseEvent(self, event): print("clicked at ", event.x, event.y) # 在当前窗口中的坐标 print("position in the screen ", event.x_root, event.y_root) # 在整个屏幕中的坐标 print("which button is clicked?", event.num) def processKeyEvent(self, event): print("keysym?", event.keysym) print("char?", event.char) print("keycode?", event.keycode) MouseKeyEventDemo()
运行结果:
('clicked at ', 109, 53) ('position in the screen ', 908, 105) ('which button is clicked?', 1) ('keysym?', 'Shift_L') ('char?', '') ('keycode?', 50)
Animations
# coding: utf-8 from Tkinter import * class AnimationDemo: def __init__(self): window = Tk() window.title("event demo") width = 250 # width canvas = Canvas(window, bg = "white", width = width, height = 50) canvas.pack() x = 0 # 初始位置 canvas.create_text(x, 30, text = "message moving?", tags = "text") dx = 3 # 每次移动距离 while True: canvas.move("text", dx, 0) canvas.after(100) # 停止100毫秒 canvas.update() if x < width: x += dx else: x = 0 canvas.delete("text") canvas.create_text(x, 30, text = "message moving?", tags = "text") window.mainloop() AnimationDemo()
Scrollbars
scrollbar = Scrollbar(frame) scrollbar.pack(side = RIGHT, fill = Y) text = Text(frame, wrap = WORD, yscrollcommand = scrollbar.set) text.pack() scrollbar.config(command = text.yview)
Standard Dialog Boxes
#coding: utf-8 import tkColorChooser import tkMessageBox import tkSimpleDialog tkMessageBox.showinfo("hello", "some info") tkMessageBox.showwarning(title, message) tkMessageBox.showerror(title, message) isYes = tkMessageBox.askyesno("askyesno", "continue?") print(isYes) name = tkSimpleDialog.askstring("askstring", "your name?") print(name) height = tkSimpleDialog.askfloat("askfloat", "your height?") print(height)