gpt4 book ai didi

python - 绑定(bind)Tkinter按钮: function takes exactly 1 positional argument (0 given)

转载 作者:行者123 更新时间:2023-12-01 04:13:27 24 4
gpt4 key购买 nike

我使用 Tkinter 在 python 中制作了一个简单的 GUI。我已经编写了它,以便当按下按钮时调用一个函数(测量)。我现在尝试绑定(bind) Enter 键来执行此功能:

root.bind("<Return>", measure)

按下 Enter 键时会出现错误:

TypeError: measure() takes no arguments (1 given)

快速搜索告诉我,如果我给函数提供参数(self),那么输入绑定(bind)将起作用,但是如果我这样做,则按钮小部件会给出错误:

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()

最佳答案

command 调用不带参数的 measure,但 bind 使用 event 参数调用它,因此 measure 必须接收这个值。

您可以使用

def mesaure(event=None): 

它将与commandbind一起使用

关于python - 绑定(bind)Tkinter按钮: function takes exactly 1 positional argument (0 given),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34609863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com