python--17 GUI编程2
GUI2 数据类型与表达式
选择列表与滚动条
1.1 Listbox列表框组件
- 演示代码:
from tkinter import *
root = Tk()
# 创建一个空列表
theLB = Listbox(root, setgrid=True)
theLB.pack()
# 往列表里添加数据
for item in ["鸡蛋", "鸭蛋", "鹅蛋", "李狗蛋"]:
theLB.insert(END, item)
theButton = Button(root, text="删除", command=lambda x=theLB: x.delete(ACTIVE))
theButton.pack()
mainloop()
- 说明:列表控件,支持单选或多选
- 创建方法:
lb = ListBox(根对象,属性列表)
- 方法:
insert(index, text)
:添加选项delete(start, [end])
:删除选项区间selection_set(start, [end])
:选中选项区间selection_get(index)
:获取某项内容size()
:获取列表框长度selection_includes()
:判断某项是否被选中
1.2 Scrollbar滚动条组件
- 说明:垂直滚动控件,常与Listbox一起使用
- 演示代码:
from tkinter import *
root = Tk()
sb = Scrollbar(root)
sb.pack(side=RIGHT, fill=Y)
lb = Listbox(root, yscrollcommand=sb.set)
for i in range(1000):
lb.insert(END, str(i))
lb.pack(side=LEFT, fill=BOTH)
sb.config(command=lb.yview)
mainloop()
1.3 OptionMenu下拉列表组件
- 演示代码:
- 功能:单击按钮展开下拉列表
# OptionMenu高级使用
from tkinter import *
def result():
#判断选择是否正确
if v.get()==items[2]:
re.config(text="答对了")
else:
re.config(text="答错了,小偷是"+items[2])
win = Tk()
win.title("逻辑推理谁是小偷") #设置窗口标题
win.configure(bg="#ffffcc")
# 创建一个OptionMenu控件
text=Text(win,width=50,height=13,bg="#ffffcc",font=14,relief="flat")
#题目
ques="一位警察,抓获四个盗窃嫌疑犯,张三、李四、王二、麻子,而他们的供词如下:\n\n张三说:“不是我偷的”。\n\n李四说:“是张三偷的”。\n\n王二说:“不是我”。\n\n麻子说:“是李四偷的”。\n\n他们四人只有一人说了真话,你知道谁是小偷吗?\n"
text.insert(END,ques) #向文本框增加内容
text.grid(row=1,columnspan=4)
text.config(state="disabled") #设置文本不可编辑
items = ("张三","李四","王二","麻子") # 答案选项
v = StringVar(win)
v.set(items[0]) #设置默认答案
om = OptionMenu(win,v,*items)
om.grid(row=2,columnspan=2)
button=Button(win,text="确定",command=result).grid(row=2,column=1,columnspan=2)
re=Label(win,padx=5,pady=5,width=60)
re.grid(row=3,column=0,columnspan=3)
win.mainloop()
1.4 Combobox组合框组件
- 演示代码:
- 功能:结合了Entry单行文本框和OptionMenu下拉列表
# Combobox组合框
from tkinter import *
from tkinter.ttk import * #引入ttk模块
win = Tk()
win.title("Combobox的创建")
label1=Label(win,text="选择管理员身份:").grid(row=1,column=0,columnspan=2,pady=10)
#管理员身份
item=("蓝色妖姬", "烈焰焚情", "寒冰幽兰", "岁岁芳华", "朝暮盈霄","陌上花开")
# 添加选择管理员身份的组合框
useroption = Combobox(win, width=12, values=item)
useroption.grid(row=1,column=2,pady=10) # 设置其在界面中出现的位置 column代表列 row 代表行
useroption.current(0) # 设置下拉列表默认显示的值,0为 item 的值
label2=Label(win,text="查看类别:").grid(row=2,pady=10,columnspan=2)
# 添加报表类别的选项
numberChosen = Combobox(win, width=12, values=("进销总览", "销量", "库存", "进售价", "账单"))
numberChosen.grid(row=2,column=2,pady=10)
numberChosen.current(0)
button=Button(win,text="提交").grid(row=3,columnspan=4,pady=10)
win.mainloop()
容器组件
2.1 Frame框架组件
- 演示代码:
from tkinter import *
from tkinter.ttk import * #引入ttk模块
if __name__ == '__main__':
win = Tk()
win.geometry('360x120')
#定义框架组件
box = Frame(width = 100,heigh = 100,relief="groove",borderwidth = 5)
box.grid(row=0,column=0,pady=10,padx=10)
txt = "你最喜欢的季节:"
Label(box, text = txt ,wraplength=320,justify = "left",font = 14).grid(columnspan=4)
select = ["春季","夏季","秋季","冬季"]
val = IntVar()
for i in range(len(select)):
Radiobutton(box,text=select[i],value = i,variable = val).grid(row=1,column = i)
win.mainloop()
- 功能:用于组织窗口中的组件
2.2 LabelFrame 标签框架组件
- 演示代码:
from tkinter import *
from tkinter.ttk import * #引入ttk模块
if __name__ == '__main__':
win = Tk()
win.geometry('360x120')
#定义LabelFrame 标签框架
txt = "你最喜欢的季节:"
box = LabelFrame(win,text= txt,width = 100,heigh = 100,relief="groove",borderwidth = 5)
box.grid(row=0,column=0,pady=10,padx=10)
select = ["春季","夏季","秋季","冬季"]
val = IntVar()
for i in range(len(select)):
Radiobutton(box,text=select[i],value = i,variable = val).grid(row=1,column = i)
win.mainloop()
2.3 Notebook选项卡组件
- 演示代码:
#Notebook选项卡
from tkinter import *
from tkinter.ttk import * #引入ttk模块
if __name__ == '__main__':
win = Tk()
win.title("日期和时间")
note = Notebook(win,width=250,heigh =150)
pane1 = Frame()
pane2 = Frame()
Checkbutton(pane2,text='显示此时钟',variable=StringVar()).pack(pady=20)
pane3 = Frame()
note.add(pane1,text="日期和时间")
note.add(pane2, text="附加始终")
note.add(pane3, text="Internet时间")
note.pack()
win.mainloop()
消息组件与对话框
3.1 Message消息组件
- 演示代码:
- 功能:显示多行文本,自动调整尺寸和换行
from tkinter import *
root = Tk()
w1 = Message(root, text="这是一则消息", width=100)
w1.pack()
w2 = Message(root, text="这是一则骇人听闻的长长长长长消息!", width=50)
w2.pack()
mainloop()
3.2 Messagebox 会话框模块
- 演示代码:
- 会话框类型:
showinfo(title, message, option)
showwarning(title, message, option)
showerror(title, message, option)
askquestion(title, message, option)
askokcancel(title, message, option)
askyesno(title, message, option)
askyesnocancel(title, message, option)
askretrycancel(title, message, option)
from tkinter import *
from tkinter.messagebox import *
root = Tk()
root.title('MessageBox示例')
showinfo(title='测试MessageBox', message='双11是中国创造的节日,无比盛大')
root.mainloop()
菜单组件
4.1 Menu菜单组件
- 演示代码:
- 参数与方法:
add_command(option)
add_cascade(option)
add_checkbutton(option)
add_radiobutton(option)
- …
from tkinter import *
root=Tk()
root.wm_title('Menu示例_1')
menubar=Menu(root)
for item in ['文件','编辑','视图','关于']:
#添加菜单项
menubar.add_command(label=item)
#显示菜单
root.config(menu=menubar)
# root['menu']=menubar
root.mainloop()
from tkinter import *
root=Tk()
root.wm_title('Menu示例_2')
menubar=Menu(root,tearoff=True)
fmenu=Menu(menubar)
for item in ['新建','打开','保存','另存为...']:
fmenu.add_command(label=item)
emenu=Menu(menubar)
for item in ['剪切','复制','粘贴','删除']:
emenu.add_command(label=item)
vmenu=Menu(menubar)
for item in ['默认视图','新式视图']:
vmenu.add_command(label=item)
amenu=Menu(menubar)
for item in ['版权信息','其他说明']:
amenu.add_command(label=item)
menubar.add_cascade(label='文件', menu=fmenu)
menubar.add_cascade(label='编辑', menu=emenu)
menubar.add_cascade(label='视图', menu=vmenu)
menubar.add_cascade(label='关于', menu=amenu)
root['menu']=menubar
root.mainloop()
进度条组件
5.1 Progressbar 进度条组件
- 演示代码:
from tkinter import *
from tkinter.ttk import *
val = 0
def add1(c):
global val
val += c
# 判断进度条的当前值是否到达最大值
if val > pro["max"]:
label.config(text="我吃饱了")
else:
vari.set(val)
win = Tk()
win.geometry("220x190")
Label(win, text="投食:").grid(row=0, column=0, columnspan=1)
# 选择投食大鱼或者小鱼,大鱼增加5点,小鱼增加1点
Button(win, text="大鱼", command=lambda: add1(5)).grid(row=0, column=1, pady=10)
Button(win, text="小鱼", command=lambda: add1(1)).grid(row=0, column=2, pady=10)
img = PhotoImage(file="cat.png") # 小猫
label = Label(win, image=img, compound=TOP, foreground="red")
label.grid(row=1, column=0, columnspan=4)
vari = IntVar() # 绑定到进度条的当前值
vari.set(0)
# 进度条显示小猫饱腹程度
pro = Progressbar(win, mode="determinate", variable=vari, max=50, length=200)
pro.grid(row=2, column=0, columnspan=4, pady=5)
win.mainloop()
5.2 左右循环滚动的进度条
- 演示代码:
from tkinter import *
from tkinter.ttk import *
win = Tk()
win.title("灵魂画师")
win.geometry("250x230")
# 添加游戏名称并应用样式
img = PhotoImage(file="game.png")
Label(win, image=img, text="灵魂画师", foreground="red", font=("华文新魏", 18), compound=BOTTOM).pack(pady=5)
pro = Progressbar(win, mode="indeterminate", value=0, max=100, length=200)
pro.pack(pady=10)
Button(win, text="进入游戏", command=pro.start(40), width=7).pack()
win.mainloop()
Canvas绘图
6.1 Canvas绘图组件
- 演示代码:
- 功能:用于绘制图形、文本,设计动画
from tkinter import *
if __name__ == '__main__':
win = Tk()
win.title("窗口中创建画布")
win.geometry("300x200")
canvas = Canvas(win,width=200,height=200,bg='#EFEFA3').pack()
win.mainloop()
鼠标键盘事件
7.1 鼠标事件
- 演示代码:
- 事件列表:
<Button-1>
:单击鼠标左键<Button-2>
:单击鼠标中键- …
from tkinter import *
import random
num=1 # 第多少关
# 随机设置颜色与众不同的方块(简称方块A)的索引
inde=random.randint(0, 99)
# 随机设置颜色
def col():
arr=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
#为保证颜色相近,color1+color2多数方块的颜色 color1+color3为与众不同的方块的颜色
color1=""
color2=""
color3=""
for i in range(4):
color1+=arr[random.randint(0,15)]
for i in range(2):
color2+=arr[random.randint(0,15)]
for i in range(2):
color3+=arr[random.randint(0,15)]
colorArr = [] #将2个颜色保存到列表里
colorArr.append("#"+color1+color2)
colorArr.append("#"+color1+color3)
return colorArr
def panduan(event):
global num
num+=1 #当前游戏关数加1
level.config(text="第"+str(num)+"关")
# 每刷新一次就需要获取一次方块A的索引
inde = random.randint(1, 100)
# 获取所有方块的颜色
colorBox=col()
for i in sqareBox:
i.config(bg=colorBox[0])
sqareBox[inde].config(bg=colorBox[1])
# 重新为方块A绑定鼠标单击事件
sqareBox[inde].bind("<Button-1>",panduan)
win = Tk()
win.geometry("270x270")
win.resizable(0,0)
sqareBox=[] # 将方块存储在列表中
colorBox=col()
for i in range(10): # 表示行
for j in range(10): # j表示列
label=Label(win,width=3,height=1,bg=colorBox[0],relief="groove")
sqareBox.append(label) # 将组件添加到列表中
label.grid(row=i,column=j)
sqareBox[inde].config(bg=colorBox[1])
sqareBox[inde].bind("<Button-1>",panduan) # 为颜色与众不同的方块天机单击事件
level=Label(win,text="第1关",font=14)
level.grid(row=11,column=0,columnspan=10,pady=10)
win.mainloop()
7.2 键盘事件
- 演示代码:
- 事件列表:
<Return>
:按下回车键<space>
:按下空格键- …
w=10 # 蛇体由小正方形组成,w为正方形的边长
x1 = 0 # 蛇头的初始位置
y1 = 10
num=5 #初始状态的蛇右5个方块组成
step=10 #蛇移动的单元距离
# 单击上键,鼠标向上移动
def up1(event):
for index,ch in enumerate(snake):
ind=len(snake)-index-1
if ind==0: #蛇头的移动
snake[ind].place(x=xx(snake[ind]),y=yy(snake[ind])- step)
else: #蛇身体的移动
snake[ind].place(x=xx(snake[ind - 1]),y=yy(snake[ind - 1]))
# 单击下键,鼠标向下移动
def down1(event):
for index,ch in enumerate(snake):
ind=len(snake)-index-1
if ind==0:
snake[ind].place(x=xx(snake[ind]),y=yy(snake[ind])+ step)
else:
snake[ind].place(x=xx(snake[ind - 1]),y=yy(snake[ind - 1]))
def left1(event): # 单击左键,鼠标向左移动
for index,ch in enumerate(snake):
ind=len(snake)-index-1
if ind==0:
snake[ind].place(x=xx(snake[ind]) - step, y=yy(snake[ind]))
else:
snake[ind].place(x=xx(snake[ind - 1]),y=yy(snake[ind - 1]))
def right1(event) :# 单击右键,鼠标向右移动
for index,ch in enumerate(snake):
ind=len(snake)-index-1
if ind==0:
snake[ind].place(x=xx(snake[ind])+ step,y=yy(snake[ind]))
else:
snake[ind].place(x=xx(snake[ind - 1]),y=yy(snake[ind - 1]))
# 避免重复代码,通过一个xx(moudle),和yy(moudle)方法获取指定组件的当前位置
def xx(module):
return int(module.winfo_geometry().split("+")[1])
def yy(module):
return int(module.winfo_geometry().split("+")[2])
# 键盘事件
from tkinter import *
win = Tk()
# 贪吃蛇
snake=[]
for i in range(num):
item1 = Frame(width=10, height=10, bg="#86E7DD")
snake.append(item1)
item1.place(x=x1, y=y1+i*w)
snake[0].config(bg="#E7869D")
win.bind("<Up>",up1) #绑定事件
win.bind("<Down>",down1)
win.bind("<Left>",left1)
win.bind("<Right>",right1)
win.mainloop()
原文地址:https://blog.csdn.net/wumingzei/article/details/140630155
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!