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.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
user3822607
  • 69
  • 1
  • 9

1 Answers1

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)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • root.after(1000, lambda x=a: update(x)) Solved the problem, thank-you. – user3822607 Feb 23 '16 at 01:45
  • @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 http://stackoverflow.com/help/someone-answers – Bryan Oakley Feb 23 '16 at 02:56