单击其他位置时,Python3 Tkinter弹出菜单不会自动关闭 [英] Python3 Tkinter popup menu not closing automatically when clicking elsewhere

查看:198
本文介绍了单击其他位置时,Python3 Tkinter弹出菜单不会自动关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行Python 3.3.3(现在我在Ubuntu上,但我也在Mac和Windows上进行开发,但尚未进行测试)。我有一个Treeview对象,该对象响应右键单击项目并显示上下文菜单,具体取决于您单击的内容...但是我注意到,如果您在原始菜单打开时在其他位置单击鼠标右键,它将打开另一个菜单。

I'm running Python 3.3.3 (and right now I'm on Ubuntu but I also develop on Mac and Windows, which I haven't yet tested). I have a Treeview object that responds to right click on items and shows a context menu depending on what you click... but I've noticed that if you right click somewhere else while the original menu is up, it just opens another one.

实际上,正常单击也不会隐藏它们。即使关闭窗口,菜单仍然保持浮动。使它们消失的唯一方法是单击选项之一。

In fact, normal clicking doesn't hide them either. Even when I close the window the menus still stay floating. The only way to get them to go away is to click one of the options.

最终结果是:

The end result is this:

菜单的代码如下:

def rightclick_listitem(self, event):
    rowitem = self.sources.identify('item', event.x, event.y)

    if rowitem == '':
        print('Right clicked an empty space.')
        return
    # user right clicked something.
    self.sources.selection_set(rowitem)
    rcmenu = Menu(self.root, tearoff=0)
    plugin_disabled=self.sources.item(rowitem, 'values')[0] == 'Disabled'
    if plugin_disabled:
        rcmenu.add_command(label='Plugin is disabled...',
                           command=self.plugin_disabled_click)
    rcmenu.add_command(label='Plugin options',state='disabled' if plugin_disabled else 'active')
    rcmenu.add_command(label='Uninstall plugin')
    rcmenu.post(event.x_root, event.y_root)

调用此代码的代码位于:

The code that calls this code is located here:

    #RIGHTMOUSE is a variable that changes based on OS due to the way Mac OSX works
    #sources is the treeview object
    self.sources.bind(RIGHTMOUSE, self.rightclick_listitem)

我到处搜寻,只有一些人问同样的问题而没有答案。总体来说,我对tkinter和python还是有些陌生,对此一无所获。我也将其他操作绑定到树视图。

I googled around and only got some people asking the same question with no answers. I'm still somewhat new to tkinter and python in general, and didn't see anything about this. I bind other actions to the treeview as well.

如果您需要更多源代码,则我的项目在这里: https://github.com/Mgamerz/Fresh-Set-of-Images (freshsetofimages.py)

If you need more sourcecode my project is here: https://github.com/Mgamerz/Fresh-Set-of-Images (freshsetofimages.py)

任何帮助

和使它出现的插件: https:/ /github.com/Mgamerz/fsoi_plugins

推荐答案

尝试调用方法 tk_popup ,而不是发布

Try calling the method tk_popup rather than post.

此外,您的代码还会发生内存泄漏,因为每次右键单击时,您都在创建一个新菜单,但从不破坏旧菜单。您只需要创建一个,然后在弹出之前对其进行重新配置。

Also, your code has a memory leak, in that each time you right-click you're creating a new menu but never destroying the old one. You only ever need to create one, and the reconfigure it before popping it up.

这篇关于单击其他位置时,Python3 Tkinter弹出菜单不会自动关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆