使用button-command发送变量(python 3.3 / tkinter)

时间:2013-12-21 18:59:53

标签: python tkinter

我想在单击按钮时更新Tkinter标签。 以下代码工作正常:

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

但是为了获得更多动态,我希望将新文本发送到changelabel-function。

我尝试了很多东西。这是我认为应该工作的,但它会立即打印“新动态文本”,而不是等待我的点击......

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

你明白我的错误吗?

1 个答案:

答案 0 :(得分:3)

您需要“隐藏”对changelabel的通话。最简单的方法是使用lambda

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

否则,当Python运行您的代码时,它会看到:

changelabel(v)

将其解释为有效的函数调用,它运行它。