Python Tkinter "stop" 函数内部的 while 循环

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

关于如何继续的任何想法?谢谢

函数 captuarPeso() 有一个 return 语句将退出 while 循环,这就是为什么你只在屏幕上打印 1 个数字的原因。

删除 return 使得你的程序卡在那个只打印 peso 的 while 循环中,因为当你对线程执行 hilo.join() 时,它实际上是在等待线程在继续之前退出,并且由于我们在第一步中摆脱了 return,线程永远不会退出,因此它再次陷入循环。为了解决这个问题,我将你的 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()

如果您需要任何解释,请告诉我,祝您节日快乐!