- 版本v1
note:代碼執(zhí)行環(huán)境:win10,python3汛骂,jupyter notebook,Tkinter
創(chuàng)建GUI程序的基本步驟為:
? 導入TK模塊
? 創(chuàng)建GUI應用程序的主窗口
? 添加控件或GUI應用程序
? 進入主事循環(huán)禾怠,等待響應用戶觸發(fā)事件
- 15種常見的TK控件
Button,Canvas,Checkbutton, Entry, Frame, Label,
Listbox, Menubutton, Menu, Message猖凛, Radiobutton,
Scale Scrollbar, Text, Toplevel, Spinbox
PanedWindow, LabelFrame, tkMessageBox
? 共同屬性
? Dimensions :尺寸
? Colors:顏色
? Fonts:字體
? Anchors:錨
? Relief styles:浮雕式
? Bitmaps:顯示位圖
? Cursors:光標的外形
? 特有屬性
- 界面布局
? Tkinter三種幾何管理方法
? pack()
? grid()
? place()
- 創(chuàng)建GUI應用程序窗口代碼模板
from tkinter import *
tk = Tk()
...
tk.mainloop()
- 簡單的GUI示例
from tkinter import *
tk = Tk()
label = Label(tk, text = 'Welcom to Python Tkinter')
button = Button(tk, text = 'Click Me')
label.pack()
button.pack()
tk.mainloop()
- 響應用戶事件示例
from tkinter import *
def processOK():
print("OK button is clinked")
def processCancel():
print("Cancel button is clinked")
def main():
tk = Tk()
btnOK = Button(tk, text = "OK", fg = "red",
command = processOK)
btnCancel = Button(tk, text = "Cancel", bg = "yellow",
command = processCancel)
btnOK.pack()
btnCancel.pack()
tk.mainloop()
main()
代碼執(zhí)行情況:
OK button is clinked
Cancel button is clinked
OK button is clinked
Cancel button is clinked
- 顯示圖片,文字大审,繪制圖形
from tkinter import *
#Tk模塊實例化余掖,定義GUI尺寸许布,和創(chuàng)建文字
tk = Tk()
canvas = Canvas(tk, width = 200, height = 200)
canvas.pack()
canvas.create_text(100,40,text = 'Welcome to Tkinter',
fill = 'blue', font = ('Times', 16) )
myImage = PhotoImage(file = "python_logo.gif")
canvas.create_image(10,70,anchor = NW, image = myImage )
canvas.create_rectangle(10,70,190,130)
tk.mainloop()
- 控制圖形移動的示例
通過鍵盤上下左右鍵控制紅色的方塊上下左右移動
from tkinter import *
#Tk模塊實例化泊柬,定義GUI尺寸
tk = Tk()
canvas = Canvas(tk, width = 400, height = 400)
canvas.pack()
#事件響應移動函數(shù)
def moverectangle(event):
if event.keysym == "Up":
canvas.move(1, 0, -5)
elif event.keysym == "Down":
canvas.move(1, 0, 5)
elif event.keysym == "Left":
canvas.move(1, -5, 0)
elif event.keysym == "Right":
canvas.move(1,5,0)
#創(chuàng)建方形函數(shù)
canvas.create_rectangle(10,10,50,50,fill="red")
#控制照片移動
#myImage = PhotoImage(file = "python_logo.gif")
#canvas.create_image(10,70,anchor = NW, image = myImage )
canvas.bind_all("<KeyPress-Up>",moverectangle)
canvas.bind_all("<KeyPress-Down>",moverectangle)
canvas.bind_all("<KeyPress-Left>",moverectangle)
canvas.bind_all("<KeyPress-Right>",moverectangle)
tk.mainloop()