Python:多线程threading应用

实现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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值