- 版本v1
note:代码执行环境:win10,python3,jupyter notebook,Tkinter
创建GUI程序的基本步骤为:
导入TK模块
创建GUI应用程序的主窗口
添加控件或GUI应用程序
进入主事循环,等待响应用户触发事件
- 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()
- 创建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()
简单GUI
- 响应用户事件示例
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()
代码执行情况:
OK button is clinked
Cancel button is clinked
OK button is clinked
Cancel button is clinked
响应用户事件
- 显示图片,文字,绘制图形
from tkinter import *
#Tk模块实例化,定义GUI尺寸,和创建文字
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()
#事件响应移动函数
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)
#创建方形函数
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()
控制图形移动
控制照片移动
网友评论