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