python - 如何向按钮添加 Shift-Click 选项

标签 python python-3.x tkinter

我是 Python 新手,尤其是 GUI Python,我正在尝试弄清楚如何向我的按钮添加两个功能。

例如,我希望用户能够: 正常点击按钮和按钮执行功能一 按住 Shift 键并单击按钮和按钮来执行第二个功能。

我正在使用 tkinter 作为 GUI。

按钮代码:

感谢任何帮助。

b1 = Button(window, text = "Import", width = 12, command = functionOne)
b1.grid(row = 0, column = 2)

最佳答案

您可以执行以下操作 - 无需设置按钮的 command 关键字参数,只需将按钮捕获的不同事件绑定(bind)到不同的函数即可。以下是有关 events and binding events 的更多信息.

import tkinter as tk


class Application(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.title("Test")
        self.geometry("128x32")
        self.resizable(width=False, height=False)

        self.button = tk.Button(self, text="Try Me")
        self.button.pack()

        self.button.bind("<Button-1>", self.normal_click)
        self.button.bind("<Shift-Button-1>", self.shift_click)

    def normal_click(self, event):
        print("Normal Click")

    def shift_click(self, event):
        print("Shift Click")


def main():

    application = Application()
    application.mainloop()

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

关于python - 如何向按钮添加 Shift-Click 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57646497/

相关文章:

python - 如何在 Tkinter 中的当前位置正确插入文本?

Python tkinter : Using a "textvariable" in a combobox seems useless

python - 我可以从 Jupyter Notebook 运行Processing.org Python sketch 并传递数据吗?

python - 如何使用 aiohttp 确定每秒请求数?

python - 将数据框与多列条件合并并进行比较

python - 在 open() 中处理 logrotate

python - 如何使用 ItemLoader 在项目中放置链接?

python - 为什么两个变量的值在 Python 中都会发生变化?

python - 检查某些内容是否不在多个列表中 - 如何使其更优雅

python - 如何将按钮小部件放在标签小部件上并确定其在 Tkinter 中的位置