0

I am attempting to pass a variable to a function that updates a screen widget. The following code works:

import tkinter as tk
import random``

def update():
    l.config(text=str(random.random()))
    root.after(1000, update)

root = tk.Tk()
l = tk.Label(text='0')
l.pack()
update()
root.mainloop()

However if I try to pass a variable it doesn't work.

import tkinter as tk
import random

def update(a):
    l.config(text=str(random.random() + a))
    root.after(1000, update)

root = tk.Tk()
l = tk.Label(text='0')
l.pack()
a=1
update(a)
root.mainloop()

and the following error appears on the screen:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1541, in __call__
    return self.func(*args)
  File "/usr/lib/python3.4/tkinter/__init__.py", line 590, in callit
    func(*args)
 TypeError: update() missing 1 required positional argument: 'a'

Is there a way around this? Need to pass the variable.

Thanks in advance.

1 Answer 1

2

If you are calling a function that accepts additional arguments, you can include those arguments in the call to after:

root.after(1000, update, a)
Sign up to request clarification or add additional context in comments.

2 Comments

root.after(1000, lambda x=a: update(x)) Solved the problem, thank-you.
@user3822607: that's odd. The lambda adds complexity without providing any extra value. Though, if you prefer that method, no harm done. However, if you prefer that answer, please consider marking it as the selected answer and possibly giving it a vote. Please see stackoverflow.com/help/someone-answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.