2

I want to update a Tkinter label when a button is clicked. The following code works fine:

import tkinter
from tkinter import *
window = tkinter.Tk()
v="start"
lbl = Label(window, text=v)
lbl.pack()
def changelabel():
    v ="New Text!"
    lbl.config(text=v)
btn=Button(window, text="Change label text", command=changelabel)
btn.pack()
window.mainloop()

But for more dynamics I would like the New text to be sent into the changelabel-function.

I've tried a lot of things. This is what I think should work, but it prints the "New dynamic text" right away, instead of waiting for my click...

import tkinter
from tkinter import *
window = tkinter.Tk()
v="start"
lbl = Label(window, text=v)
lbl.pack()
def changelabel(v):
    lbl.config(text=v)
v ="New, dynamic text!"
btn=Button(window, text="Change label text", command=changelabel(v))
btn.pack()
window.mainloop()

Do you understand my error?

Enthuziast
  • 1,195
  • 1
  • 10
  • 18

1 Answers1

4

You need to "hide" the call to changelabel. The easiest way to do this is to use a lambda:

btn=Button(window, text="Change label text", command=lambda: changelabel(v))

Otherwise, when Python runs through your code, it sees this:

changelabel(v)

Interpreting it as a valid function call, it runs it.