动态创建的按钮tkinter的引用函数迭代 [英] referencing function iterations for dynamically created buttons tkinter
问题描述
我已经动态创建了按钮并将其设置为调用脚本功能,因此当单击 Test 1
时,将执行 script_1
,同样为 script_2
进行测试2
,依此类推...
但在时单击测试1
或测试2
,执行 script_0
。似乎 val = i.get()
每次总是返回值0。有没有办法获取当前的 i值
?
I have created buttons dynamically and set them to call script function so when Test 1
is clicked script_1
is executed, likewise Test 2
for script_2
and so on...
but when Test 1
or Test 2
is clicked script_0
is executed. It appears val = i.get()
always returns the value 0 each time. Is there a way to get the current i value
?
函数
def script():
if running:
i = IntVar()
val = i.get()
subprocess.Popen(['python', 'script_' + str(val) + '.py'])
root.update()
按钮
for i in range(3):
button.append(tk.Button(root, text="Test " + str(i + 1), font=(None, 16), command=lambda i=i: script()))
button[-1].grid(column=0, row=i + 1)
推荐答案
那是因为您在前一行初始化 i
,而IntVar始终初始化为0。您需要将 i
传递为脚本的参数:
That's because you initialize i
the line before, and IntVar always initializes to 0. You need to pass i
as an argument to your script:
from Tkinter import Button, IntVar, Tk
import subprocess
def script(i):
subprocess.Popen(['python', 'script_' + str(i) + '.py'])
root.update()
root = Tk()
button = []
for i in range(3):
button.append(Button(root, text="Test " + str(i + 1), font=(None, 16), command=lambda i=i: script(i)))
button[-1].grid(column=0, row=i + 1)
root.mainloop()
这对我来说分别正确弹出script_0.py,1,2。考虑将root包裹在一个类中是一种很好的做法(类似于继承Tk),并将按钮作为 __ init __
的一部分。
This correctly popens script_0.py,1,2 respectively for me. Consider wrapping root in a class as good practice (some like to inherit Tk), and making the buttons a part of __init__
.
这篇关于动态创建的按钮tkinter的引用函数迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!