Skip to main content
 首页 » 编程设计

python之在 python 代码中创建的窗口中更改字体

2025年05月04日11bhlsheji

更改用 python 代码创建的窗口中的字体。

我有一些工作的 python 代码在窗口中显示 MMDDYYYY HH:MM:ss 我想在日期和时间上方添加其他文本,同时增加字体大小(数据和时间 MMDDYYYY HH: MM:SS).我尝试添加不同的文本和字体大小,但这会使我的代码无法运行。

#!/usr/bin/env python 
# -*- coding: utf-8  -*- 
 
import pygtk 
pygtk.require('2.0') 
import gtk 
import time 
 
class Clock: 
 
    def __init__(self): 
        window = gtk.Window(gtk.WINDOW_TOPLEVEL) 
        window.connect("destroy", lambda w: gtk.main_quit()) 
        window.set_title("mmddyyyyhhmmss-Clock") 
        self.label = gtk.Label() 
        window.add(self.label) 
        window.set_border_width(10) 
        window.show_all () 
 
    def update(self): 
 
        self.label.set_text(time.strftime('%m/%d/%Y-%H%M%S')) 
        return True  #needed to keep the update method in the schedule 
 
def main(): 
    gtk.main() 
 
if __name__ == "__main__": 
    clock = Clock() 
    gtk.timeout_add(200, clock.update)  #add to the main loop scheduled tasks 
    main() 

请您参考如下方法:

使用标记很可能会满足您的需要。首先,在标签上启用它。然后不使用 set_text,而是使用 set_markup:

self.label.set_use_markup(True) 
t = time.strftime('%m/%d/%Y-%H%M%S') 
self.label.set_markup('<span size="18000">The time:</span> ' + t) 

作为引用:GTK使用的标记语言是Pango .