我使用Tkinter在python中创建了一个简单的GUI。 我已经写过它,这样当按下按钮时,会调用一个函数(测量)。 我现在尝试绑定Enter键以使用以下方式执行此功能:
root.bind("<Return>", measure)
按下Enter键时出现错误:
TypeError: measure() takes no arguments (1 given)
快速搜索告诉我,如果我给函数提供参数(self),那么输入绑定将起作用,但是如果我这样做,那么按钮小部件会给出错误:
TypeError: measure() takes exactly 1 positional argument (0 given)
有快速解决方法吗? Python初学者,如果这是一个非常简单的问题,请道歉。
import datetime
import csv
from tkinter import *
from tkinter import messagebox
root = Tk()
winx = 480
winy = 320
virtual_reading = '1.40mm'
def measure():
todays_date = datetime.date.today()
try:
get_tool_no = int(tool_no_entry.get())
if get_tool_no <= 0:
messagebox.showerror("Try Again","Please Enter A Number")
else:
with open("thickness records.csv", "a") as thicknessdb:
thicknessdbWriter = csv.writer(thicknessdb, dialect='excel', lineterminator='\r')
thicknessdbWriter.writerow([get_tool_no] + [todays_date] + [virtual_reading])
thicknessdb.close()
except:
messagebox.showerror("Try Again","Please Enter A Number")
tool_no_entry.delete(0, END)
root.resizable(width=FALSE, height=FALSE)
root.geometry('%dx%d' % (winx,winy))
root.title("Micrometer Reader V1.0")
record_button = Button(root,width = 30,
height = 8,
text='Measure',
fg='black',
bg="light grey", command = measure)
record_button.place(x = 350, y = 100, anchor = CENTER)
reading_display = Label(root, font=("Helvetica", 22), text = virtual_reading)
reading_display.place(x = 80, y =80)
tool_no_entry = Entry(root)
tool_no_entry.place(x = 120, y = 250, anchor=CENTER)
tool_no_entry.focus_set()
root.bind("<Return>", measure)
root.mainloop()
答案 0 :(得分:1)
您使用了函数measure
两次,一次需要一个参数,第二次需要0参数。你应该用lambda包装它:
root.bind("<Return>", lambda x: measure())
答案 1 :(得分:1)
command
在没有参数的情况下调用measure
,但bind
使用event
参数调用它,因此measure
必须接收此值。
您可以使用
def mesaure(event=None):
它将与command
和bind