網站首頁 編程語言 正文
問題描述
有些小伙伴在使用python做GUI界面的時候可能想添加這么一個小功能,就是在界面的某個角落動態的顯示當前的時間,本文將介紹具體方法。
方式一(使用組件的after方法)
代碼如下所示:
import time
import tkinter
from tkinter import Label
?
?
def get_time():
? ? time2 = time.strftime('%Y-%m-%d %H:%M:%S')
? ? clock = Label(top, text=time2, font=28)
? ? clock.place(x=15, y=120)
? ? clock.after(1000,get_time)
?
top = tkinter.Tk()
top.geometry('500x300')
get_time()
top.mainloop()
after方法的作用是每隔一段時間調用函數一次,需要添加兩個參數,第一個參數為時間間隔,第二個參數為所調用的函數,上述代碼中的1000指的是1000毫秒,也就是一秒鐘調用一次get_time函數。
方式二(新建線程)
這個方法需要用到threading模塊,作用是創建一個新的線程。
代碼如下:
import time
import tkinter
from tkinter import Label
import threading
?
top = tkinter.Tk()
top.geometry('500x300')
clock = Label(top,text='',font=28)
clock.place(x=15, y=120)
def f():
? ? while True:
? ? ? ? clock.configure(text=time.strftime('%Y-%m-%d %H:%M:%S'))
? ? ? ? time.sleep(1)
thread = threading.Thread(target=f)
thread.setDaemon(True)
thread.start()
top.mainloop()
其中thread為新開辟的一個線程,thread.setDaemon(True)這句代碼的作用呢是設置守護線程,當主線程結束時更新時間的線程也結束,如果不設置的話關閉界面則會報錯,因為你還有一個線程在執行。
總結
原文鏈接:https://blog.csdn.net/daitianjun/article/details/126335394
相關推薦
- 2023-07-30 vscode自定義用戶代碼片段
- 2022-07-02 Python列表1~n輸出步長為3的分組實例_python
- 2022-10-15 flask路由分模塊管理及自定義restful響應格式詳解_python
- 2022-08-15 Python類的定義繼承調用比較方法技巧_python
- 2022-04-25 .Net?Core?Aop之IResourceFilter的具體使用_實用技巧
- 2022-08-19 SpringMVC異常處理器
- 2023-01-12 一文帶你入木三分地理解字符串KMP算法以及C++實現_C 語言
- 2022-10-04 在shell腳本中激活conda虛擬環境的方法總結_linux shell
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支