我正在使用pygtk并搜索将字体和颜色对话框组合在一起的最佳方法,这是最pythonic的方法吗?
答案 0 :(得分:1)
您必须更改小部件样式的“基本”和“文本”部分。您还可以编辑“前景”属性。一些有用的简写方法来更改从gtk.Widget继承的样式属性是:
widget.modify_fg(state, color)
widget.modify_bg(state, color)
widget.modify_base(state, color)
widget.modify_text(state, color)
gtk.Label,gtk.Button,gtk.Paned,gtk.Frame等无窗口小部件(参见FAQ 3.5)尽管从gtk.Widget继承,但不允许更改其背景和基色,因为这些属性不会他们不存在。如果要获取它们,则需要在添加此属性的gtk.EventBox中插入窗口小部件。示例:
import gtk
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect("destroy", gtk.mainquit)
label = gtk.Label("one, two, testing...")
eb = gtk.EventBox()
eb.add(label)
eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("blue"))
window.add(eb)
window.show_all()
gtk.main()
同时建议您阅读此gtk.gdk.Window — on-screen display areas in the target window system.
另一方面,pygtk具有更改颜色和更改或选择字体的对话框。
示例1:更改字体
import gtk
import pango
class PyApp(gtk.Window):
def __init__(self):
gtk.Window.__init__(self)
self.set_size_request(300, 150)
self.set_position(gtk.WIN_POS_CENTER)
self.connect("destroy", gtk.main_quit)
self.set_title("Font Selection Dialog")
self.label = gtk.Label("The only victory over love is flight.")
button = gtk.Button("Select font")
button.connect("clicked", self.on_clicked)
fix = gtk.Fixed()
fix.put(button, 100, 30)
fix.put(self.label, 30, 90)
self.add(fix)
self.show_all()
def on_clicked(self, widget):
fdia = gtk.FontSelectionDialog("Select font name")
response = fdia.run()
if response == gtk.RESPONSE_OK:
font_desc = pango.FontDescription(fdia.get_font_name())
if font_desc:
self.label.modify_font(font_desc)
fdia.destroy()
PyApp()
gtk.main()
示例2:更改标签的颜色
import gtk
class PyApp(gtk.Window):
def __init__(self):
super(PyApp, self).__init__()
self.set_size_request(300, 150)
self.set_position(gtk.WIN_POS_CENTER)
self.connect("destroy", gtk.main_quit)
self.set_title("Color Selection Dialog")
self.label = gtk.Label("The only victory over love is flight.")
button = gtk.Button("Select color")
button.connect("clicked", self.on_clicked)
fix = gtk.Fixed()
fix.put(button, 100, 30)
fix.put(self.label, 30, 90)
self.add(fix)
self.show_all()
def on_clicked(self, widget):
cdia = gtk.ColorSelectionDialog("Select color")
response = cdia.run()
if response == gtk.RESPONSE_OK:
colorsel = cdia.colorsel
color = colorsel.get_current_color()
self.label.modify_fg(gtk.STATE_NORMAL, color)
cdia.destroy()
PyApp()
gtk.main()
希望它有所帮助。