本帖最后由 damiaa 于 2025-3-8 22:52 编辑
【 STM32MP135F-DK测评】+(10)python3+gtk3+制作日期时钟
主题如上,使用python3 gtk3 使用时钟日期库
代码如下:
import gi
import time
import datetime
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GObject, GLib
class MyWindow(Gtk.Window):
def __init__(self):
super().__init__(title="Time test")
# 设置窗口属性
self.set_default_size(200, 100)
self.set_position(Gtk.WindowPosition.CENTER)
self.set_border_width(10)
# 创建一个垂直布局盒子
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
self.add(vbox)
# 创建一个标签用于显示日期
self.date_label = Gtk.Label(justify=Gtk.Justification.CENTER)
vbox.pack_start(self.date_label, True, True, 0)
#获取日期和星期
now = datetime.datetime.now()
str_date =now.strftime('%Y-%m-%d')+" "
self.date_label.set_text(str_date)
# 创建一个标签用于显示时间
self.time_label = Gtk.Label(justify=Gtk.Justification.CENTER)
vbox.pack_start(self.time_label, True, True, 0)
# 初始化时间显示
self.update_time()
# 设置一个定时器,每秒更新时间
self.timeout_id = GLib.timeout_add_seconds(1, self.update_time)
def update_time(self):
# 获取当前时间
current_time = time.strftime("%H:%M:%S")
# 更新标签内容
self.time_label.set_text(current_time)
# 返回True以保持定时器运行
return True
def on_destroy(self, widget):
# 移除定时器
GLib.source_remove(self.timeout_id)
Gtk.main_quit()
win = MyWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
效果如下:
2