referencing function iterations for dynamically created buttons tkinter

南笙酒味 提交于 2019-12-25 09:19:05

问题


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?

function

def script():
    if running:
        i = IntVar()
        val = i.get()
        subprocess.Popen(['python', 'script_' + str(val) + '.py'])
    root.update()

Button

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)

回答1:


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

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__.



来源:https://stackoverflow.com/questions/40749969/referencing-function-iterations-for-dynamically-created-buttons-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!