如何将 Shift-Click 选项添加到按钮

问题描述:

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

I am new to Python, and especially GUI Python, and am trying to figure out how to add two functions to my button.

例如,我希望用户能够:正常点击按钮和按钮执行功能一shift-click 按钮和按钮执行功能二.

For example, I want user to be able to: click on button normally and button to execute function one shift-click on button and button to execute function number two.

我将 tkinter 用于 GUI.

I am using tkinter for GUI.

按钮代码:

感谢任何帮助.

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

你可以这样做 - 而不是设置按钮的 command 关键字参数,只需将按钮捕获的不同事件绑定到不同的职能.这里有一些关于事件和绑定事件的更多信息.

You can do something like this - Instead of setting the button's command keyword argument, just bind different events captured by the button to different functions. Here's some more info about 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())