实现demo:
两个线程,点击开始按钮,开始循环;点击停止,结束上一个线程;
代码:
from tkinter import *
import time
import threading
root = Tk()
root.geometry("360x360+400+300")
root.title("中午吃什么???")
but_1 = Button(root,text = "米加菜")
but_1.place(x=30,y=30,width=80,height=80)
but_2 = Button(root,text = "烤肉饭")
but_2.place(x=30,y=140,width=81,height=80)
but_3 = Button(root,text = "玉米")
but_3.place(x=30,y=250,width=80,height=80)
but_4 = Button(root,text = "肉夹馍")
but_4.place(x=140,y=30,width=80,height=80)
but_6 = Button(root,text = "水饺")
but_6.place(x=140,y=250,width=80,height=80)
but_7 = Button(root,text = "面条")
but_7.place(x=250,y=30,width=80,height=80)
but_8 = Button(root,text = "地瓜")
but_8.place(x=250,y=140,width=80,height=80)
but_9 = Button(root,text = "饿着吧")
but_9.place(x=250,y=250,width=80,height=80)
eatlist = [but_1,but_4,but_9,but_2,but_7,but_3,but_8,but_6]
isloop = False
stopsign = False #stopsign=true结束rond()
stopid = None
def rond():
global isloop
global stopid
if isloop == True:
return
i = 1
if isinstance(stopid,int):
i = stopid
while True:
time.sleep(0.1)
for x in eatlist:
x['bg'] = "white"
eatlist[i]['bg'] = "red"
i += 1
print("当前i为:",i)
if i>=len(eatlist):
i = 0
if stopsign == True:
isloop = False
stopid = i
break
def stop():
global stopsign
if stopsign == True:
return
stopsign = True
def newtask():
global isloop
global stopsign
stopsign = False
t = threading.Thread(target=rond)
t.start()
isloop = True
but_start = Button(root,text="开始",command=newtask)
but_stop = Button(root,text="停止",command=stop)
but_start.place(x=130,y=160,width=40,height=40)
but_stop.place(x=190,y=160,width=40,height=40)
root.mainloop()