[英]Binding Tkinter button: function takes exactly 1 positional argument (0 given)
I have made a simple GUI in python using Tkinter.我使用 Tkinter 在 python 中制作了一个简单的 GUI。 I've written it so that when a button is pressed a function (measure) is called.
我写它是为了当一个按钮被按下时一个函数(测量)被调用。 I'm now trying to bind the Enter key to also carry out this function using:
我现在正在尝试绑定 Enter 键以使用以下方法执行此功能:
root.bind("<Return>", measure)
This gives the error when Enter is pressed:按下 Enter 时会出现以下错误:
TypeError: measure() takes no arguments (1 given)
A quick search tells me that if I give the function the argument (self) then the enter bind will work, however if I do this then the button widget gives the error:快速搜索告诉我,如果我为函数提供参数 (self),则输入绑定将起作用,但是如果我这样做,则按钮小部件会给出错误:
TypeError: measure() takes exactly 1 positional argument (0 given)
Is there a quick fix for this?有没有快速解决这个问题的方法? Python beginner, so apologies if this is a really simple question.
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()
You used the function measure
twice, one requires one argument, second requires 0 argument.您使用了函数
measure
两次,第一个需要一个参数,第二个需要 0 个参数。 You should wrap it with lambda:你应该用 lambda 来包装它:
root.bind("<Return>", lambda x: measure())
command
calls measure
without arguments but bind
calls it with event
argument so measure
have to receive this value. command
调用没有参数的measure
,但bind
使用event
参数调用它,所以measure
必须接收这个值。
You can use您可以使用
def mesaure(event=None):
and it will work with command
and bind
它将与
command
和bind
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.