Python中使用gi.repository模块实现单选按钮的功能
发布时间:2024-01-16 03:09:00
Python中使用gi.repository模块实现单选按钮的功能,需要使用Gtk模块。下面是一个使用例子。
首先,需要导入gi.repository和Gtk模块:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
然后,创建一个Gtk.Window对象,并设置关闭窗口时退出程序:
win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
接下来,创建一个Gtk.Box对象,并设置布局方式为垂直布局:
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6) win.add(box)
然后,创建一个Gtk.RadioButton对象,并添加到Box中:
button1 = Gtk.RadioButton.new_with_label_from_widget(None, "Option 1")
button1.connect("toggled", on_button_toggled, "1")
box.pack_start(button1, True, True, 0)
创建其他的RadioButton对象,并添加到Box中:
button2 = Gtk.RadioButton.new_from_widget(button1)
button2.set_label("Option 2")
button2.connect("toggled", on_button_toggled, "2")
box.pack_start(button2, True, True, 0)
button3 = Gtk.RadioButton.new_from_widget(button1)
button3.set_label("Option 3")
button3.connect("toggled", on_button_toggled, "3")
box.pack_start(button3, True, True, 0)
创建一个标签对象,并添加到Box中:
label = Gtk.Label()
label.set_text("No option selected")
box.pack_start(label, True, True, 0)
最后,定义一个toggled事件处理函数,当单选按钮状态发生改变时,更新标签的文本内容:
def on_button_toggled(button, name):
if button.get_active():
label.set_text("Option %s selected" % name)
最后,显示窗口并启动主循环:
win.show_all() Gtk.main()
完整的代码如下:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
def on_button_toggled(button, name):
if button.get_active():
label.set_text("Option %s selected" % name)
win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
win.add(box)
button1 = Gtk.RadioButton.new_with_label_from_widget(None, "Option 1")
button1.connect("toggled", on_button_toggled, "1")
box.pack_start(button1, True, True, 0)
button2 = Gtk.RadioButton.new_from_widget(button1)
button2.set_label("Option 2")
button2.connect("toggled", on_button_toggled, "2")
box.pack_start(button2, True, True, 0)
button3 = Gtk.RadioButton.new_from_widget(button1)
button3.set_label("Option 3")
button3.connect("toggled", on_button_toggled, "3")
box.pack_start(button3, True, True, 0)
label = Gtk.Label()
label.set_text("No option selected")
box.pack_start(label, True, True, 0)
win.show_all()
Gtk.main()
以上代码实现了一个简单的窗口,其中包含三个单选按钮和一个标签。当用户选择一个单选按钮时,标签会显示相应的选项被选中。这里使用了Gtk.RadioButton和Gtk.Label对象来实现单选按钮和标签的功能。
这是使用gi.repository模块实现单选按钮功能的一个简单例子,希望对你有所帮助。
