python建立窗体后,使用mainloop显示窗体,如何使用多线程在窗体中实时显示时间?

class MainForm(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent,
                          id,
                          title="test",
                          pos=(200, 150),
                          size=(900, 600))
        MainForm_Panel = wx.Panel(self)
        MainForm_Font = wx.Font(11, wx.DEFAULT, wx.DEFAULT, wx.NORMAL)

        self.MainForm_SystemTime_Label = wx.StaticText(MainForm_Panel,
                                                       id,
                                                       label=datetime.datetime.now().strftime(GUIParameter.system_time),
                                                       pos=(705, 540),
                                                       style=wx.TE_RIGHT)

 

if __name__ == '__main__':
    app = wx.App()
    frame = MainForm(parent=None, id=-1)
    frame.Show()
    app.MainLoop()

你开的多线程,将窗口的对象作为参数传进去,然后修改对象的控件就行了

import threading

import wx
import datetime
class MainForm(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent,
                          id,
                          title="test",
                          pos=(200, 150),
                          size=(900, 600))
        self.id = id
        self.MainForm_Panel = wx.Panel(self)
        MainForm_Font = wx.Font(11, wx.DEFAULT, wx.DEFAULT, wx.NORMAL)

        self.MainForm_SystemTime_Label = wx.StaticText(self.MainForm_Panel,
                                                       self.id,
                                                       label=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                                       pos=(705, 540),
                                                       style=wx.TE_RIGHT)

def task(frame):
    while 1:
        frame.MainForm_SystemTime_Label.Label = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

if __name__ == '__main__':
    app = wx.App()
    frame = MainForm(parent=None, id=-1)
    frame.Show()
    t = threading.Thread(target=task, args=(frame,))
    t.setDaemon(True)
    t.start()

    app.MainLoop()

如果对你有帮助,可以点击我这个回答右上方的【采纳】按钮,给我个采纳吗,谢谢

如果对时间精度要求不高,比如精确到秒的时钟,可以使用wx的定时器实现,如果要求较高,比如秒表,则需要线程技术。使用线程更新窗体显示内容时,有一个关键,就是需要借助于wx.CallAfter()来完成。下面的代码,演示了时钟和秒表。时钟一直再走,按空格键启动或停止秒表,按Esc键秒表归零。

#-*- coding: utf-8 -*-

import wx
import time
import threading

class mainFrame(wx.Frame):
    """时钟和秒表演示类"""
    
    def __init__(self):
        """构造函数"""
        
        wx.Frame.__init__(self, None, -1, title='定时器和线程')
        self.SetBackgroundColour(wx.Colour(224, 224, 224)) # 设置窗口背景
        self.SetSize((320, 300)) # 设置窗口大小
        self.Center() # 窗口居中
        
        # 设置时钟和秒表的字体字号
        font = wx.Font(30, wx.DECORATIVE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, 'Monaco')
        
        # 用静态文本框模拟数字时钟
        self.clock = wx.StaticText(self, -1, '08:00:00', pos=(50,50), size=(200,50), style=wx.TE_CENTER|wx.SUNKEN_BORDER)
        self.clock.SetForegroundColour(wx.Colour(0, 224, 32))
        self.clock.SetBackgroundColour(wx.Colour(0, 0, 0))
        self.clock.SetFont(font)
        
        # 用静态文本框模拟秒表
        self.watch = wx.StaticText(self, -1, '0:00:00.0', pos=(50,150), size=(200,50), style=wx.TE_CENTER|wx.SUNKEN_BORDER)
        self.watch.SetForegroundColour(wx.Colour(0, 224, 32))
        self.watch.SetBackgroundColour(wx.Colour(0, 0, 0))
        self.watch.SetFont(font)
        
        self.sec_last = None    # 定义最后的秒数,用于判断时钟显式是否需要更新
        self.is_start = False   # 秒表是否启动
        self.t_start = None     # 秒表启动的初始时间
        
        # 启动定时器,定时间隔50毫秒(仅用于时钟)
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)
        self.timer.Start(50)
        
        # 启动秒表线程(不用定时器,是因为秒表需要更高的精度)
        thread_sw = threading.Thread(target=self.watch_thread)
        thread_sw.setDaemon(True)
        thread_sw.start()
        
        # 绑定键盘事件,按空格键启动或停止秒表,按Esc键秒表归零
        self.Bind(wx.EVT_KEY_DOWN, self.on_keydown)
        
    def on_timer(self, evt):
        """定时器函数"""
        
        t = time.localtime()
        if t.tm_sec != self.sec_last:
            self.clock.SetLabel('%02d:%02d:%02d'%(t.tm_hour, t.tm_min, t.tm_sec))
            self.sec_last = t.tm_sec
        
    def on_keydown(self, evt):
        """键盘事件函数"""
        
        if evt.GetKeyCode() == wx.WXK_SPACE:
            self.is_start = not self.is_start
            self.t_start= time.time()
        elif evt.GetKeyCode() == wx.WXK_ESCAPE:
            self.is_start = False
            self.watch.SetLabel('0:00:00.0')
        
    def watch_thread(self):
        """秒表的线程函数"""
        
        while True:
            if self.is_start:
                n = int(10*(time.time() - self.t_start))
                hh, mm, ss, deci = int(n/36000), int(n/600)%60, int(n/10)%60, n%10
                wx.CallAfter(self.watch.SetLabel, '%d:%02d:%02d.%d'%(hh, mm, ss, deci))
            time.sleep(0.02)

if __name__ == "__main__":
    app = wx.App()
    frame = mainFrame()
    frame.Show(True)
    app.MainLoop()

 

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632