【问题标题】:Can't stop a while with Tkinter buttons无法使用 Tkinter 按钮停止一段时间
【发布时间】:2019-12-26 10:27:25
【问题描述】:

我有两个按钮开始停止,当我点击开始按钮时,我想通过一段时间,但是当我想停止它时, Tkinter 窗口被阻止,我无法点击停止按钮,因为整个窗口都被阻止了。

下面是我的代码:

s = 1
def Start():
   while(s==1):
      #do something
def Stop():
   global s
   s = 0

btn_Start= Button(root, text = 'Start',width=9, height=2, command = Start).place(x=2,y=2)
btn_Stop = Button(root, text = 'Stop',width=9, height=2, command = Stop).place(x=2,y=42)

有谁知道我怎样才能停止这段时间?

编辑:-------- 还是一样的错误

【问题讨论】:

标签: python python-3.x python-2.7 tkinter


【解决方案1】:

如果要与活动窗口同时运行该功能,则必须使用线程方法将其连接。

threading 方法创建一个线程,该线程创建一个单独的程序执行。

这是您的解决方案,

import tkinter
import threading
from tkinter import *

root = Tk()

s = 1

def Start():
    while(s==1):
        print(s)
        #do something


def thread():
    global t
    t = threading.Thread(target = Start)
    t.start()

def Stop():
   global s
   s = 0
   t.join()
   print("Stopped")

btn_Start= Button(root, text = 'Start',width=9, height=2, command = thread).place(x=2,y=2)
btn_Stop = Button(root, text = 'Stop',width=9, height=2, command = Stop).place(x=2,y=42)

在上面的程序中,Start() 被分配为线程。因此,当按下Start 按钮时,命令thread() 将通过执行Start() 函数创建一个新线程。 当 Stop() 函数将被调用时,t.join() 将包含该线程到您的 Stop() 函数执行中。

在这里您可以找到线程模块文档, https://docs.python.org/3/library/threading.html#module-threading

【讨论】:

  • 它没有用。我在我的问题中添加了一张照片,看看会发生什么。可以看看吗?
  • 我的错,我忘了更改 btn_start 的命令。它正在工作
  • 还有一个问题,时间并没有停止。我认为它没有采用相同的's'
  • 's'被定义为全局变量。因此,当每个函数被调用时,它使用's'的赋值。如果while循环没有停止,你可以使用布尔变量,否则while 循环内的条件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
  • 2020-04-11
  • 1970-01-01
  • 2019-04-18
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多