使用Tkinter Listbox作为打印的替代方式

2024-06-17 14:50:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Tkinter做了一个GUI程序,做了一个Listbox,为了在里面打印一些句子,我用了Listbox的.insert方法,但问题是,程序在后台运行,然后把所有的东西都打印在一起,这会造成一个滞后问题,而这不是我想要的。现在我要实现的是在代码中触发每个项后立即插入它,例如:l1.insert(END,'Hi')----a=1+1----l1.insert(END,'Hi again') 我希望“Hi”在列表框中可见,然后程序计算a,然后再次插入“Hi”,而不是一次执行所有操作并打印所有内容。 这是可能的还是我应该寻找另一种方法?请指定一些可行的方法。你知道吗


Tags: 方法代码程序l1tkinterguihi后台
1条回答
网友
1楼 · 发布于 2024-06-17 14:50:51

当您希望在GUI应用程序的后台运行计算时,您需要使用多线程或多处理。这是因为您的GUI将在等待函数运行时冻结。如果使用面向对象编程(OOP)结构构建GUI,这些过程会变得更容易。使用OOP可以让你把GUI传递给你的线程,一旦它准备好了,它就会写“HI”或者“HI”,而不会产生延迟问题。下面是我制作的一个简单的OOP线程GUI示例。你知道吗

import tkinter as tk
from threading import Thread
import time
import datetime


class OOP:
    def __init__(self):
        self.win = tk.Tk()
        self.win.attributes('-topmost', True)
        self.win.geometry(newGeometry="%dx%d%+d%+d" % (45, 40, 50, 50))
        self.start_time = time.time()
        self.current_pay = tk.StringVar()
        self.time_output = tk.StringVar()
        tk.Label(self.win, textvariable=self.time_output, bg="#450609", fg='white').pack(expand=1, fill='both')
        tk.Label(self.win, textvariable=self.current_pay, bg="#450609", fg='white').pack(expand=1, fill='both')
        self.create_thread()

    def calculate_pay(self):
        pay_rate = 2000.00 #made up hourly wage for Stack Overflow post
        now = time.time()
        elapsed = datetime.timedelta(seconds=(now - self.start_time))
        hours = int(elapsed.seconds/3600)
        minutes = int(((elapsed.seconds / 3600) - hours) * 60)
        seconds = int(((((elapsed.seconds / 3600) - hours) * 60) - minutes) * 60)
        self.current_pay.set('$%.2f' % ((elapsed.seconds / 3600) * pay_rate))
        self.time_output.set('{}:{}:{}'.format(hours, minutes, seconds))

    def method_in_a_thread(self):
        while True:
            self.calculate_pay()
            time.sleep(.3)
            self.win.lift()

    def create_thread(self):
        self.run_thread = Thread(target=self.method_in_a_thread)
        self.run_thread.start()


app = OOP()
app.win.mainloop()

这个GUI已经在几行上进行了修改,但是我认为它可以帮助您展示我如何创建一个永远运行的线程(您的线程不必通过任何方式)并使用该线程来更新可见的GUI!在不到50行,你可以有一个时钟,显示你已经在工作多久,你已经赚了多少钱,迄今为止,在一天XD!你知道吗

相关问题 更多 >