Ewan321
Ewan321

Reputation: 21

Binding Tkinter button: function takes exactly 1 positional argument (0 given)

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

Upvotes: 1

Views: 1266

Answers (2)

furas
furas

Reputation: 142759

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

Upvotes: 2

Assem
Assem

Reputation: 12107

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

Upvotes: 2

Related Questions