此篇博文用hreading和tkinter模块实现转盘游戏,一起学习
效果图如下
'''
转盘游戏:
设置12个选项 分别为 笔墨纸砚、琴棋书画、梅兰竹菊、风花雪月
随机定位到按钮
'''
import threading
import tkinter
import time
# 1.建立窗口
root = tkinter.Tk()
root.title('转盘游戏')
root.minsize(300,300)
# 2.摆放按钮
btn1 = tkinter.Button(root,text='笔',bg='white')
btn1.place(x=20,y=20,width=50,height=50)
btn2 = tkinter.Button(root,text='墨',bg='white')
btn2.place(x=90,y=20,width=50,height=50)
btn3 = tkinter.Button(root,text='纸',bg='white')
btn3.place(x=160,y=20,width=50,height=50)
btn4 = tkinter.Button(root,text='砚',bg='white')
btn4.place(x=230,y=20,width=50,height=50)
btn5 = tkinter.Button(root,text='琴',bg='white')
btn5.place(x=230,y=90,width=50,height=50)
btn6 = tkinter.Button(root,text='棋',bg='white')
btn6.place(x=230,y=160,width=50,height=50)
btn7 = tkinter.Button(root,text='书',bg='white')
btn7.place(x=230,y=230,width=50,height=50)
btn8 = tkinter.Button(root,text='画',bg='white')
btn8.place(x=160,y=230,width=50,height=50)
btn9 = tkinter.Button(root,text='梅',bg='white')
btn9.place(x=90,y=230,width=50,height=50)
btn10 = tkinter.Button(root,text='兰',bg='white')
btn10.place(x=20,y=230,width=50,height=50)
btn11 = tkinter.Button(root,text='竹',bg='white')
btn11.place(x=20,y=160,width=50,height=50)
btn12 = tkinter.Button(root,text='菊',bg='white')
btn12.place(x=20,y=90,width=50,height=50)
## 2.1将所有的选项放到列表中 目的:为了操作这些选项
button_list = [btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,btn10,btn11,btn12]
## 2.2 设置一个停止标记
stop_sign = False
stop_id = None
# 3.定义一个函数: 1)循环选项;2)改变选项的颜色
def round():
global stop_id
i = 1
if isinstance(stop_id,int):
i = stop_id
while True:
time.sleep(0.3)
for x in button_list:
x['bg'] = 'white'
button_list[i]['bg'] = 'red'
i += 1
print('当前的i为:',i)
if i>= len(button_list):
i = 0
if stop_sign == True:
stop_id = i
break
# 4.定义停止的方法
def stop():
global stop_sign
if stop_sign == True:
return
stop_sign = True
# 5.定义开始的方法 (开启线程,单独跑一个循环的函数)
def start():
global stop_sign
stop_sign = False
t = threading.Thread(target=round)
t.start() # 创建线程并启动
# 6.设置按钮
btn_start = tkinter.Button(root,text='开始',command=start) # command = start 附加了start函数的功能按钮
btn_start.place(x=90,y=125,width=50,height=50)
btn_stop = tkinter.Button(root,text='停止',command=stop) # command = stop 附加了stop函数的功能按钮
btn_stop.place(x=160,y=125,width=50,height=50)
# 7.显示窗口
root.mainloop()
# 这里用线程的原因:
# 主线程是实现 点击按钮 开始旋转 停止 按钮在停止旋转,本身逻辑就不太好实现。一个主线程就是 按钮的逻辑(点击开始和点击停止),然后子线程实现 旋转的逻辑