[英]Python Tkinter “stop” a while loop inside function
我有一个 Python 程序,它使用 Tkinter 实时显示一个值( capturarpeso()
函数中的 var peso
)。 但是capturarPeso()
中的 while 循环不起作用,循环仅在第一次起作用,然后脚本“等待”。
如果我删除 TK 组件,它会完美运行。 我简化了脚本:
import tkinter as tk
from tkinter import *
import threading
import random
def capturarPeso():
global peso
while True:
peso = random.randrange(0, 101, 2)
print (peso)
return(peso)
def capturarPesoHilo():
hilo = threading.Thread(target=capturarPeso, name=None, group=None, args=(), kwargs=None, daemon=True)
hilo.start()
hilo.join()
class ActualizarPeso(Label):
def __init__(self, parent, *args, **kwargs):
Label.__init__(self, parent, *args, **kwargs)
self.tick()
def tick(self):
self.config(text= peso)
self.after(500, self.tick)
capturarPesoHilo()
window = tk.Tk()
window.title('Capturador pesos')
window.resizable(width=False, height=False)
pesoLabel = ActualizarPeso(window, font="Arial 60", fg="red", bg="black", width=8, height= 1)
pesoLabel.grid(row=15, column=0)
window.mainloop()
关于如何继续的任何想法? 谢谢
function captuarPeso()
有一个return
语句,它将退出 while 循环,这就是为什么你只会在屏幕上打印 1 个数字。
删除return
会使您的程序陷入仅打印peso
的 while 循环中,因为当您对线程执行hilo.join()
时,它实际上是在等待线程退出后再继续,并且因为我们摆脱了 return in第一步,线程永远不会退出,因此它再次陷入循环。 为了解决这个问题,我将您的 while 循环更改为while self.peso:= -999:
并在调用.mainloop()
后设置self.peso = -999
这将告诉程序:用户已退出 Tkinter 界面,退出我的循环.
既然您使用class
将一些 tkinter gui 放入,为什么不把它全部放入呢? 一般来说,大多数人会将整个 tkinter 接口放在 class 中,我已经继续为您重新构建了程序,但尝试保留与原始程序一样多的内容,以便您可以分析它并查看它是如何工作的。
import tkinter as tk
import threading
import random
import time
class ActualizarPeso:
def __init__(self):
self.window = tk.Tk()
self.window.title('Capturador pesos')
self.window.resizable(width=False, height=False)
self.pesoLabel = self.crearLabel()
self.peso = 0
self.tick()
hilo1 = self.capturarPesoHilo()
self.window.mainloop()
self.peso = -999
hilo1.join()
def crearLabel(self):
pesoLabel = tk.Label(self.window, font="Arial 60", fg="red", bg="black", width=8, height=1)
pesoLabel.grid(row=15, column=0)
return pesoLabel
def tick(self):
self.pesoLabel.config(text=self.peso)
self.pesoLabel.after(500, self.tick)
def capturarPeso(self):
while self.peso != -999:
self.peso = random.randrange(0, 101, 2)
print(self.peso)
time.sleep(1)
def capturarPesoHilo(self):
hilo = threading.Thread(target=self.capturarPeso)
hilo.start()
return hilo
ActualizarPeso()
如果您需要解释一下,请告诉我,祝您节日快乐!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.