在Python中使用回车键触发按钮单击

时间:2018-04-26 14:13:52

标签: python tkinter

请提前原谅我,因为我对Python很陌生。我正在将这个代码放在一个非常简单的速率计算器中,并希望在按下Enter键的时候将程序计算到总计(执行计算命令)。 Python返回一个错误,说没有定义Calculate,但是我已经在上面定义了几行。有什么想法吗?

import tkinter
from tkinter import ttk
from tkinter import *

    root = Tk()
    root.withdraw()

class Adder(ttk.Frame):

"""The adders gui and functions."""
    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.init_gui()


    def on_quit(self):
        """Exits program."""
        quit()

    def calculate(self, *args):
        """Calculates the sum of the two inputted numbers."""
        num1 = int(self.num1_entry.get())
        num2 = float(self.num2_entry.get())
        num3 = ((num1/2000) * num2)
        self.answer_label['text'] = num3





    def init_gui(self):
        self.root.title('Breakbulk Rate Calculator')
        self.root.option_add('*tearOff', 'FALSE')

        self.grid(column=0, row=0, sticky='nsew')

        self.menubar = tkinter.Menu(self.root)

        self.menu_file = tkinter.Menu(self.menubar)
        self.menu_file.add_command(label='Exit', command=self.on_quit)

        self.menu_edit = tkinter.Menu(self.menubar)

        self.menubar.add_cascade(menu=self.menu_file, label='File')
        self.menubar.add_cascade(menu=self.menu_edit, label='Edit')

        self.root.config(menu=self.menubar)

        self.num1_entry = ttk.Entry(self, width=5)
        self.num1_entry.grid(column=1, row = 2)

        self.num2_entry = ttk.Entry(self, width=5)
        self.num2_entry.grid(column=3, row=2)

        self.calc_button = ttk.Button(self, text='Calculate',
                command=self.calculate)
        self.calc_button.grid(column=0, row=3, columnspan=4)

        self.answer_frame = ttk.LabelFrame(self, text='Answer',
                height=100)
        self.answer_frame.grid(column=0, row=4, columnspan=4, sticky='nesw')

        self.answer_label = ttk.Label(self.answer_frame, text='')
        self.answer_label.grid(column=0, row=0)

        # Labels that remain constant throughout execution.
    ttk.Label(self, text='Breakbulk Rate Calculator').grid(column=0, row=0,
            columnspan=4)
    ttk.Label(self, text='Weight').grid(column=0, row=2,
            sticky='w')
    ttk.Label(self, text='Rate').grid(column=2, row=2,
            sticky='w')

    ttk.Separator(self, orient='horizontal').grid(column=0,
            row=1, columnspan=4, sticky='ew')

    for child in self.winfo_children():
        child.grid_configure(padx=5, pady=5)


root.bind('<Return>', calculate)


if __name__ == '__main__':
    root = tkinter.Tk()
    Adder(root)
    root.mainloop()

2 个答案:

答案 0 :(得分:1)

我已稍微重新组织了您的代码,因此当您按下按钮或按 Enter 时,它现在调用calculate方法。

import tkinter as tk
from tkinter import ttk

class Adder(ttk.Frame):
    """The adders gui and functions."""
    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.init_gui()

    def on_quit(self):
        """Exits program."""
        tk.quit()

    def calculate(self, *args):
        """Calculates the sum of the two inputted numbers."""
        num1 = int(self.num1_entry.get())
        num2 = float(self.num2_entry.get())
        num3 = ((num1/2000) * num2)
        self.answer_label['text'] = num3

    def init_gui(self):
        self.root.title('Breakbulk Rate Calculator')
        self.root.option_add('*tearOff', 'FALSE')

        self.grid(column=0, row=0, sticky='nsew')

        self.menubar = tk.Menu(self.root)

        self.menu_file = tk.Menu(self.menubar)
        self.menu_file.add_command(label='Exit', command=self.on_quit)

        self.menu_edit = tk.Menu(self.menubar)

        self.menubar.add_cascade(menu=self.menu_file, label='File')
        self.menubar.add_cascade(menu=self.menu_edit, label='Edit')

        self.root.config(menu=self.menubar)

        self.num1_entry = ttk.Entry(self, width=5)
        self.num1_entry.grid(column=1, row = 2)

        self.num2_entry = ttk.Entry(self, width=5)
        self.num2_entry.grid(column=3, row=2)

        self.calc_button = ttk.Button(self, text='Calculate',
                command=self.calculate)
        self.calc_button.grid(column=0, row=3, columnspan=4)

        self.answer_frame = ttk.LabelFrame(self, text='Answer',
                height=100)
        self.answer_frame.grid(column=0, row=4, columnspan=4, sticky='nesw')

        self.answer_label = ttk.Label(self.answer_frame, text='')
        self.answer_label.grid(column=0, row=0)

        # Labels that remain constant throughout execution.
        ttk.Label(self, text='Breakbulk Rate Calculator').grid(column=0, row=0,
                columnspan=4)
        ttk.Label(self, text='Weight').grid(column=0, row=2,
                sticky='w')
        ttk.Label(self, text='Rate').grid(column=2, row=2,
                sticky='w')

        ttk.Separator(self, orient='horizontal').grid(column=0,
                row=1, columnspan=4, sticky='ew')

        for child in self.winfo_children():
            child.grid_configure(padx=5, pady=5)

        self.root.bind('<Return>', lambda event: self.calculate())


if __name__ == '__main__':
    root = tk.Tk()
    Adder(root)
    root.mainloop()

要为.bind创建一个具有正确签名的回调,我使用了一个简单地丢弃传递给它的Event对象的lambda函数。

我还摆脱了邪恶的from tkinter import *通配符导入。

答案 1 :(得分:0)

问题来自你的代码部分

root.bind('<Return>', calculate)

将其更改为

root.bind('<Return>', self.calculate)

它会起作用。