【问题标题】:Stopping a function once a button is pressed tkinter按下按钮后停止功能tkinter
【发布时间】:2020-05-27 18:56:55
【问题描述】:

我有一个“开始”按钮,它可以启动一个功能,但也想要一个可以结束该特定功能的按钮,有没有办法可以做到这一点,这是我的代码:

from tkinter import *
from tkinter.ttk import *

root = Tk()
root.geometry('900x900')
def start():
    for count in range(100):
        Label(root,text='hi').pack()

def stop():
    #What code should I use to stop 'def start'
    print('')

Button(root,text='stop',command=lambda: stop).pack()
Button(root,text='start',command=lambda: start()).pack()

root.mainloop()

提前致谢

【问题讨论】:

标签: python function tkinter pycharm tk


【解决方案1】:

您可以尝试使用库线程并同时运行两个线程。

这里我留下代码。

from tkinter import *
from tkinter.ttk import *
from time import sleep
import threading
from threading import Thread
root = Tk()
root.geometry('900x900')

def start():
    global flag
    for count in range(100):
        if flag:break
        print(flag)
        Label(root,text='hi').pack()
        sleep(1)

def stop():
    global flag
    flag=True
    print(flag)
if __name__=='__main__':
    flag=False
    thread=[]
    Button(root,text='stop',command=lambda: Thread(target=stop).start()).pack()
    Button(root,text='start',command=lambda: Thread(target=start).start()).pack()
    root.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 2019-04-18
    • 2019-03-08
    • 1970-01-01
    相关资源
    最近更新 更多