简体   繁体   English

在python中按下键盘上的“ enter”键时,如何设置特定的动作

[英]How do I set a specific action to happen when the “enter” key on my keyboard is pressed in python

I am making a python calculator with GUI for school. 我正在为学校制作带有GUI的python计算器。

I have got some basic code from the internet and I have to customize it by changing things around. 我从互联网上获得了一些基本代码,并且必须通过更改周围内容来对其进行自定义。 So far I have added a DEL button, a ^2 button and a sqrt() button. 到目前为止,我已经添加了DEL按钮, ^2按钮和sqrt()按钮。

I now want that if I type in an equation on my keyboard, eg "2*4", and press Enter it will simulate as pressing the equals button. 现在,我希望如果我在键盘上键入一个等式,例如“ 2 * 4”,然后按Enter ,它将模拟为按下等号按钮。 I am having trouble finding out how to get python to register me clicking the Enter and then give me an answer. 我在查找如何使python注册我的过程中遇到了麻烦,单击Enter ,然后给我一个答案。

This is the code: 这是代码:

from __future__ import division
from math import *
from functools import partial
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk
class MyApp(tk.Tk):
    def __init__(self):
        # the root will be self
        tk.Tk.__init__(self)
        self.title("Magic")
        # use width x height + x_offset + y_offset (no spaces!)
        #self.geometry("300x150+150+50")
        # or set x, y position only
        self.geometry("+150+50")
        self.memory = 0
        self.create_widgets()
    def create_widgets(self):
        # this also shows the calculator's button layout
        btn_list = [
        '7',  '8',  '9',  '*',  'AC',
        '4',  '5',  '6',  '/',  'x²',
        '1',  '2',  '3',  '-',  '√x',
        '0',  '.',  '=',  '+',  'DEL' ]
        rel = 'ridge'
        # create all buttons with a loop
        r = 1
        c = 0
        for b in btn_list:
            # partial takes care of function and argument
            cmd = partial(self.calculate, b)
            tk.Button(self, text=b, width=5, relief=rel,
                command=cmd).grid(row=r, column=c)
            c += 1
            if c > 4:
                c = 0
                r += 1
        # use an Entry widget for an editable display
        self.entry = tk.Entry(self, width=37, bg="white")
        self.entry.grid(row=0, column=0, columnspan=5)

    def undo():
            new_string = whole_string[:-1]
            print(new_string)
            clear_all()
            display.insert(0, new_string)

    def calculate(self, key):
        if key == '=':
            # here comes the calculation part
            try:
                result = eval(self.entry.get())
                self.entry.insert(tk.END, " = " + str(result))
            except:
                self.entry.insert(tk.END, "")
        elif key == 'AC':
            self.entry.delete(0, tk.END)
        elif key == 'x²':
            self.entry.insert(tk.END, "**")
            # extract the result
        elif key == '√x':
            self.memory = self.entry.get()
            self.entry.delete(0, tk.END)
            self.entry.insert(tk.END, "sqrt(")
            self.entry.insert(tk.END, self.memory)
            self.entry.insert(tk.END, ")")
        elif key == 'DEL':
            self.memory = self.entry.get()
            self.entry.delete(0, tk.END)
            self.entry.insert(tk.END, self.memory[:-1])

        else:# previous calculation has been done, clear entry
            if '=' in self.entry.get():
                self.entry.delete(0, tk.END)
            self.entry.insert(tk.END, key)

app = MyApp()
app.mainloop()

You can use bind() to assign function to Entry which will be executed when you press Enter 您可以使用bind()将函数分配给Entry ,当您按Enter时将执行该函数

Example: 例:

import tkinter as tk

def on_return(event):
    print('keycode:', event.keycode)
    print('text in entry:', event.widget.get())

root = tk.Tk()

e = tk.Entry(root)
e.pack()
e.bind('<Return>', on_return)   # standard Enter
e.bind('<KP_Enter>', on_return) # KeyPad Enter

root.mainloop()

In your code it can be - for test 在您的代码中可以-用于测试

self.entry = tk.Entry(self, width=37, bg="white")
self.entry.grid(row=0, column=0, columnspan=5)

self.entry.bind('<Return>', lambda event:print("ENTER:", event.widget.get()))
self.entry.bind('<KP_Enter>', lambda event:print("ENTER:", event.widget.get()))

If you have class method def on_return(self, event): then 如果您有类方法def on_return(self, event):然后

self.entry.bind('<Return>', self.on_return)
self.entry.bind('<KP_Enter>', self.on_return)

  1. Events and Bindings 事件和绑定

  2. Key names 键名

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我希望在按下回车键时屏幕被清除/完全变黑。 我该怎么做? - I want the screen to be cleared/completely black when the enter key is pressed. How would I do that? 如果循环中未提供输入(或按下回车键),如何在 python 中结束无限循环 - How do I end an infinite loop in python if no input(or the enter key is pressed) is provided in the loop 在将文本输入文本小部件后按Enter键时如何执行回调? - How do I execute a callback when the Enter key is pressed after entering text into a Text widget? 如果在 kivy python 中按下一个键(回车),则执行一个函数 - Do a function if a key(enter) is pressed in kivy python 我如何做到在按下一个键并释放另一个键的同时发生动作? (pygame的/蟒) - How do I make it so that while a key is pressed and another key is released an action occurs? (Pygame/python) 如何在 python 中创建一个键盘侦听器,它将返回按下的键的字符? - How do I create a keyboard listener in python that will return the character of the pressed key? 我如何知道 QTextEdit 上的 Enter 键何时被按下 - How can I know when the Enter key was pressed on QTextEdit 在 Python 的键盘中按下特定字符/数字时如何按下按钮? - How to press a button when a specific character/number is pressed in keyboard on Python? 在python中没有按下键后如何执行操作? - How to do an action after a key hasn't been pressed in python? 如何检查Python是否按下Enter键? - How to check that the Enter key was pressed in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM