在 Tkinter 中单击按钮上的弹出菜单 [英] Popup Menu on Button Click in Tkinter

查看:50
本文介绍了在 Tkinter 中单击按钮上的弹出菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码有一个小问题.我的界面上需要一个弹出菜单,该菜单不会在按下鼠标右键时弹出,而是在单击按钮(tkinter 小部件)时弹出.

I have a slight problem in my code. I need a popup menu on my interface, that pops up, not when the right mouse button is pressed, but when a button (tkinter widget) is clicked.

一个例子是:http://effbot.org/zone/tkinter-popup-menu.htm

但是,我想在与按钮相同的坐标处创建弹出菜单,而不是事件坐标.

However, instead of the event coordinates, I want to create the popupmenu at the same coordinates as the button.

self.popup_menu.tk_popup(x_button, y_button, 0)

问题是,当我移动界面窗口或滚动滚动条(我的界面中有一个)并再次单击按钮时,弹出菜单不是在按钮所在的确切位置创建的.似乎 .tk_popup 只取窗口坐标而不是画布坐标.

The problem is that, when I move my interface window or scroll the scollbar (I have one in my interface) and click on the button again, the popupmenu is created not at the exact position where the button is. It seems that .tk_popup is only taking the window coordinates rather than the canvas coordinates.

有人知道解决方案吗?

下面是一个例子:

from Tkinter import *

root = Tk()

popup = Menu(root, tearoff=0)
popup.add_command(label="Main Product")
popup.add_command(label="Side Product")

def popupm(x, y):
     try:
           popup.tk_popup(x, y, 0)
     finally:
           popup.grab_release()

x = 10
y = 15
bt = Button(root, text='Menu', command= lambda: popupm(x , y))
bt.place(x = 10, y = 15)

root.mainloop()

您好!

推荐答案

按钮有几个方法可以满足您的需求:.winfo_rootx() 和 .winfo_rooty()这是一个工作示例:

Buttons have a couple methods that give you what you want: .winfo_rootx() and .winfo_rooty() Here is a working example:

from Tkinter import *

root = Tk()

popup = Menu(root, tearoff=0)
popup.add_command(label="Main Product")
popup.add_command(label="Side Product")

def popupm(bt):
     try:         
        x = bt.winfo_rootx()
        y = bt.winfo_rooty()
        popup.tk_popup(x, y, 0)
     finally:
           popup.grab_release()

bt = Button(root, text='Menu')
bt.configure(command = lambda: popupm(bt))
bt.place(x = 10, y = 15)

root.mainloop()

我在 python3 中测试过,如果它没有转换为 2,抱歉.如果您有任何问题或需要帮助调整一下,请告诉我们.

I tested it in python3, sorry if it doesn't translate to 2. Let us know if you have any troubles with it or need help adapting it a bit.

这篇关于在 Tkinter 中单击按钮上的弹出菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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