类中的tkinter按钮不会绑定到键

时间:2018-02-05 08:46:47

标签: python button tkinter bind

总的noob无法使tkinter按钮绑定到键盘。

我试图将它们绑定在main()和 init ()中。

我尝试了一系列语法排列。什么都行不通。

我已经尝试过,直到按钮获得焦点然后点击。什么都不发生。

任何人都有关于如何做的秘密内幕信息?

from tkinter import *
from tkinter.ttk import Frame, Button, Style

class Example(Frame):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.btn_convert.bind("<Return>", self.convert)
    # -----------------------------------------------

    def convert(self):
        print("enter pressed")
    # -----------------------------------------------

    def quit(self):
        self.root.destroy()
        exit()
    # -----------------------------------------------

    def initUI(self):

        self.master.title("Weight Converter")
        self.pack(fill=BOTH, expand=True)
        self.frame_btn = Frame(self)
        self.frame_btn.pack(fill=BOTH, expand=True, padx=20, pady=5)
        self.btn_convert=Button(self.frame_btn, text="Convert", command=self.convert)
        self.btn_convert.pack(side=LEFT, padx=5, pady=5)

        self.btn_close1=Button(self.frame_btn, text="Close", command=quit)
        self.btn_close1.pack(side=LEFT, padx=5, pady=5)

def main():

    root = Tk()
    root.geometry("300x250+300+200")
    app = Example()
    root.bind("<Return>", lambda event: root.convert())
    root.mainloop()


if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:2)

替换:

root.bind("<Return>", lambda event: root.convert())

使用:

root.bind("<Return>", lambda event: app.convert())

或:

#in case you have multiple instances of Tk
app.bind("<Return>", lambda event: app.convert())
app.focus_set()

由于convertExample实例(app)而非Tk实例(root)的方法。另外,请确保object.bind用于(root以上两行,而app位于最后一行)通过手动对焦或调用焦点object.focus_set()

以下是基于按键的print s“Enter”或“Escape”的示例:

import tkinter as tk


class App(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.button = tk.Button(self, text="Event")
        self.button.bind('<Return>', lambda evt : self.event_handler(True))
        self.button.focus_set()             # ensure initial focus is on the button
        self.button.pack()


    def event_handler(self, is_enter):
        if is_enter:
            my_string = "Enter"
        else:
            my_string = "Escape"
        print(my_string)


if __name__ == '__main__':
    root = tk.Tk()
    app = App(root)
    app.button.bind('<Escape>', lambda evt : app.event_handler(False))
    app.pack()
    root.mainloop()

所有键的演示示例

下面的演示应显示所有键的按键:

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def on_key_press(event):
    global label
    label['text'] = event.keysym


if __name__ == '__main__':
    root = tk.Tk()
    label = tk.Label(root)
    root.bind('<KeyPress>', on_key_press)
    label.pack()
    root.mainloop()

答案 1 :(得分:1)

要添加常规“按Enter以运行convert”绑定,您应将其应用于root。要添加更多基于焦点的绑定,您应该基于每个按钮应用它们,如下所示:

from tkinter import *
from tkinter.ttk import Frame, Button, Style

class Example(Frame):
    def __init__(self):
        super().__init__()
        self.initUI()
    # -----------------------------------------------

    def convert(self):
        print("enter pressed")
    # -----------------------------------------------

    def quit(self):
        print("quit pressed")
        self.destroy()
        exit()
    # -----------------------------------------------

    def initUI(self):
        self.master.title("Weight Converter")
        self.pack(fill=BOTH, expand=True)
        self.frame_btn = Frame(self)
        self.frame_btn.pack(fill=BOTH, expand=True, padx=20, pady=5)
        self.btn_convert=Button(self.frame_btn, text="Convert", command=self.convert)
        self.btn_convert.pack(side=LEFT, padx=5, pady=5)

        self.btn_close1=Button(self.frame_btn, text="Close", command=quit)
        self.btn_close1.pack(side=LEFT, padx=5, pady=5)
        # When tab focus is on the "Close" button, change Return behaviour.
        self.btn_close1.bind("<Return>", lambda event: self.quit())

def main():
    root = Tk()
    root.geometry("300x250+300+200")
    app = Example()
    root.bind("<Return>", lambda event: app.convert())
    root.mainloop()


if __name__ == '__main__':
    main()