Defining TkInter StringVars in a loop

自古美人都是妖i 提交于 2021-02-10 20:22:29

问题


My program iterates through a list of values and creates a new frame with relevant information. I want to add a button to refresh the values in just one of the frames. The following image is a mockup of what I'm trying to achieve, where the "reload" button grabs new data for just one printer.

I'm running into an issue where only the last values get updated. The following code is an approximation of what I was trying:

import tkinter as tk
from tkinter import ttk

def buttonupdate(x):
    return int(x.get())+1

root=tk.Tk()

values=[0,0,0,0,0,0,0]
stringVarList=[]

for i,item in enumerate(values):
    newStringVar=tk.StringVar()
    newStringVar.set(item)
    stringVarList.append(newStringVar)

    valueLabel=tk.Label(root, textvariable=stringVarList[i])
    valueLabel.grid(row=0,column=i)

    button=tk.Button(root, text="+1", command=lambda:stringVarList[i].set(buttonupdate(stringVarList[i])))
    button.grid(row=1, column=i)

root.mainloop()

With this code, only the last value gets updated, no matter which button I press.

What can I try instead? Thank you.

来源:https://stackoverflow.com/questions/53735061/defining-tkinter-stringvars-in-a-loop

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