notCoder
notCoder

Reputation: 37

missing 1 required positional argument: 'times' in function

I keep getting the error:

missing 1 required positional argument: 'times'

While my code is:

import tkinter as tk
from tkinter import messagebox

top = tk.Tk()

top.geometry("200x100")

def helloCallBack(times):
   times = times + 1
   messagebox.showinfo( "Clicked!!1", "Hello World")
   print("Clicked button " + str(times) + " times")
   

B = tk.Button(top, text ="Hello", command = helloCallBack)
B2 = tk.Button(top, text="Exit", command=top.destroy)

B2.pack(pady=20)
B.pack()
top.mainloop()

I tried to find an answer, but they used classes so I couldn't find an answer.

Upvotes: 0

Views: 946

Answers (2)

gsb22
gsb22

Reputation: 2180

Agreed with the above answer. If you want to maintain how many times the button is clicked, you have to take out the times variable from the function.

BUT if you really need to pass args to method, you should use lambda or partials.

https://www.delftstack.com/howto/python-tkinter/how-to-pass-arguments-to-tkinter-button-command/

import tkinter as tk
from tkinter import messagebox

top = tk.Tk()

top.geometry("200x100")

def helloCallBack(times):
    times = times + 1
    messagebox.showinfo("Clicked!!1", "Hello World")
    print("Clicked button " + str(times) + " times")


B = tk.Button(top, text="Hello", command=lambda: helloCallBack(0))
B2 = tk.Button(top, text="Exit", command=top.destroy)

B2.pack(pady=20)
B.pack()
top.mainloop()

Upvotes: 1

Barmar
Barmar

Reputation: 781088

times shouldn't be a parameter to the function, it should be a global variable so it keeps its value between calls.

times = 0

def helloCallBack():
    global times
    times = times + 1
    messagebox.showinfo( "Clicked!!1", "Hello World")
    print("Clicked button " + str(times) + " times")

Upvotes: 2

Related Questions