如何解决RuntimeError:本次显示项目中没有运行事件循环?

问题描述 投票:0回答:1

嘿,我面临着在终端上运行时间戳的问题。这是我的代码,当我尝试运行该代码时,

它会弹出这样的错误: 运行时错误:没有运行事件循环 sys:1:运行时警告:从未等待过协程“TimeDisplayApp.display_time”

我可以知道解决方法吗?

import tkinter as tk
import asyncio
import datetime
import pytz

class TimeDisplayApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Time Display App")

        self.display_time_button = tk.Button(root, text="Display Time", command=self.start_display)
        self.display_time_button.pack()

        self.close_time_display_button = tk.Button(root, text="Close Time Display", command=self.stop_display)
        self.close_time_display_button.pack()
        self.close_time_display_button.config(state=tk.DISABLED)

        self.timestamp_label = tk.Label(root, text="")
        self.timestamp_label.pack()

        self.display_task = None
        self.update_gui()

    def start_display(self):
        self.display_time_button.config(state=tk.DISABLED)
        self.close_time_display_button.config(state=tk.NORMAL)
        self.display_task = asyncio.create_task(self.display_time())

    def stop_display(self):
        self.display_time_button.config(state=tk.NORMAL)
        self.close_time_display_button.config(state=tk.DISABLED)
        if self.display_task:
            self.display_task.cancel()
            self.timestamp_label.config(text="Time display stopped")

    async def display_time(self):
        kl_timezone = pytz.timezone('Asia/Kuala_Lumpur')
        while True:
            kl_time = datetime.datetime.now(kl_timezone)
            formatted_time = kl_time.strftime("%Y-%m-%d %H:%M:%S %Z")
            self.timestamp_label.config(text="Current time in Kuala Lumpur: " + formatted_time)
            await asyncio.sleep(1)

    def update_gui(self):
        self.root.update()
        self.root.after(1000, self.update_gui)

if __name__ == "__main__":
    root = tk.Tk()
    app = TimeDisplayApp(root)
    root.mainloop()

解决显示的问题,一旦单击“显示时间按钮”,时间戳可以在终端上不断更新。

python datetime tkinter asynchronous
1个回答
0
投票

尝试一次

import asyncio
import tkinter as tk
import pytz
import datetime

class TimeDisplayApp:
def __init__(self, root):
    self.root = root
    self.root.title("Time Display")
    self.timestamp_label = tk.Label(root, text="")
    self.timestamp_label.pack()
    self.update_time()
async def display_time(self):
    kl_timezone = pytz.timezone('Asia/Kuala_Lumpur')
    while True:
        kl_time = datetime.datetime.now(kl_timezone)
        formatted_time = kl_time.strftime("%Y-%m-%d %H:%M:%S %Z")
        self.timestamp_label.config(text="Current time in Kuala Lumpur: " + formatted_time)
        await asyncio.sleep(1)
  def update_time(self):
    asyncio.create_task(self.display_time())
def main():
root = tk.Tk()
app = TimeDisplayApp(root)
root.mainloop()

if __name__ == "__main__":
 main()
© www.soinside.com 2019 - 2024. All rights reserved.