bind python measure() takes exactly positional argument

我只是一个虾纸丫 提交于 2021-02-04 21:29:47

问题


I have made a simple GUI in python using Tkinter. 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:

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

This gives the error when Enter is pressed:

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:

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.

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

回答1:


command calls measure without arguments but bind calls it with event argument so measure have to receive this value.

You can use

def mesaure(event=None): 

and it will work with command and bind




回答2:


You used the function measure twice, one requires one argument, second requires 0 argument. You should wrap it with lambda:

root.bind("<Return>", lambda x: measure())


来源:https://stackoverflow.com/questions/34609863/bind-python-measure-takes-exactly-positional-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!