如何在Python中停止由tkinter触发的循环

时间:2016-04-25 17:56:30

标签: python tkinter

我是Python新手,对tkinter更是如此,我决定尝试通过Tkinter为无限循环创建一个启动和停止按钮。不幸的是,一旦我点击开始,它就不允许我点击停止。开始按钮保持缩进,我认为这是因为它触发的功能仍在运行。如何让第二个按钮停止代码?

import tkinter

def loop():
    global stop
    stop = False
    while True:
        if stop == True:
            break
        #The repeating code
def start():
    loop()
def stop():
    global stop
    stop = True

window = tkinter.Tk()
window.title("Loop")
startButton = tkinter.Button(window, text = "Start", command = start)
stopButton = tkinter.Button(window, text = "Pause", command = stop)
startButton.pack()

1 个答案:

答案 0 :(得分:2)

您正在呼叫library(dplyr) df <- data_frame(country = c("india", "INDIA", "uae", "UAE", "US", "Germany", "Some other Country"), val = c(1:7)) some.countries <- df %>% filter(grepl("india|uae", country, ignore.case = TRUE)) some.countries #Source: local data frame [4 x 2] # # country val # (chr) (int) #1 india 1 #2 INDIA 2 #3 uae 3 #4 UAE 4 。长话短说,while True有它自己的事件循环。因此,无论何时调用一些长时间运行的进程,它都会阻止此事件循环,您无法执行任何操作。您应该使用Tk()

我通过向after提供属性来避免使用global

e.g。 -

window