Skip to main content
 首页 » 编程设计

python之使用 Python 在 Gtk 中将其他 CheckMenuItems 的事件状态设置为 False

2025年02月15日25lautakyan007

我已经为 Ubuntu 编写了一个应用程序指示器(基本上是 wifi 和电池图标旁边的一个图标)来设置关闭盖子的 Action 。它工作得很好,但我想添加一个复选标记 ✓ 以查看哪个状态处于事件状态。这可以使用 CheckMenuItems 而不是 Gtk 中的 MenuItems 来完成。问题是,就我而言,CheckMenuItems 的事件状态是互斥的。 IE。当一个处于事件状态时,另一个不处于事件状态。我列出了代码中最相关的部分。

def build_menu(): 
    menu = gtk.Menu() 
 
    item_suspend = gtk.CheckMenuItem('Set lid to suspend') 
    item_suspend.connect('activate', set_lid_suspend) 
    menu.append(item_suspend) 
 
    item_nothing = gtk.CheckMenuItem('Set lid to nothing') 
    item_nothing.connect('activate', set_lid_nothing) 
    menu.append(item_nothing) 
 
    menu.show_all() 
    return menu 
 
def set_lid_suspend(menuItem): 
    call([os.path.join(__location__, "setLidSuspend.sh")]) 
    noot.update("<b>Set lid to suspend.</b>", "", None) 
    noot.show() 
 
    # adjusting the checkmarks 
    menu = menuItem.get_parent() 
    for item in menu.get_children(): # loop over all children 
        if item.get_label() == 'Set lid to nothing': 
            item.set_active(False) 
            break 
    menuItem.set_active(True) 
 
def set_lid_nothing(menuItem): 
    call([os.path.join(__location__, "setLidNothing.sh")]) 
    noot.update("<b>Set lid to nothing.</b>", "", None) 
    noot.show() 
 
     # adjusting the checkmarks 
    menu = menuItem.get_parent() 
    for item in menu.get_children(): # loop over all children 
        if item.get_label() == 'Set lid to suspend': 
            print(item) 
            item.set_active(False) 
            break 
    print("broke from nothing") 
    menuItem.set_active(True) 

问题是,当我使用 appIndicator 并调用这两种方法之一时,一切都很好并且表现良好;但是当我选择另一种方法时,它们将永远在它们之间交替循环。有谁知道我做错了什么?

此外,这是查找菜单的 menuItems 的正确方法吗?我很难相信没有这样的方法来替代我使用的 for 循环。

请您参考如下方法:

我认为您使用了错误的方法。我会使用 RadioMenuItem .然后,如果 radiomenuitem 的事件状态为 False,我将阻止“更改”代码。这将导致类似这样的结果:

def build_menu(): 
    menu = gtk.Menu() 
 
    item_suspend = gtk.RadioMenuItem('Set lid to suspend') 
    item_suspend.connect('activate', set_lid_suspend) 
    menu.append(item_suspend) 
 
    item_nothing = gtk.RadioMenuItem('Set lid to nothing') 
    item_nothing.connect('activate', set_lid_nothing) 
    menu.append(item_nothing) 
 
    item_suspend.join_group(item_nothing) 
 
    menu.show_all() 
    return menu 
 
def set_lid_suspend(menuItem): 
    if menuItem.get_active() == False: 
       return 
    call([os.path.join(__location__, "setLidSuspend.sh")]) 
    noot.update("<b>Set lid to suspend.</b>", "", None) 
    noot.show() 
 
 
def set_lid_nothing(menuItem): 
    if menuItem.get_active() == False: 
       return 
    call([os.path.join(__location__, "setLidNothing.sh")]) 
    noot.update("<b>Set lid to nothing.</b>", "", None) 
    noot.show() 

由于您发布的代码不完整,我无法对此进行肯定的测试。试试看,然后告诉我。