How to create an “array” of multiple tkinter Scale widgets with Python?

喜你入骨 提交于 2020-01-24 20:31:07

问题


I am trying to create a GUI using Python 3.2.3 and the tkinter module. I need an "array" of Scale widgets but cannot for the life of me figure out how to return the values except by creating the Scale widgets one at a time and having a separate function for each one called by its command keyword argument passing the var.

I can loop the widget creation bit and increment the row and column parameters as necessary but can't figure out how to retrieve the values of the Scale widgets.

In "Basic" each widget would have an index which could be used to address it but I cannot find how anything similar is implemented in Python. Even worse - just with a single Scale widget, I used:

from Tkinter import *

master = Tk()

w = Scale(master, from_=0, to=100)
w.pack()

w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()

mainloop()


#To query the widget, call the get method:

w = Scale(master, from_=0, to=100)
w.pack()

print w.get()

And got the response:

AttributeError: 'NoneType' object has no attribute 'get'

I am assuming this is some kind of version issue.


回答1:


Are you sure you are using Python 3? Your example is Python 2. This simple example works with 1 widget:

from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=100,command=lambda event: print(w.get())) 
w.pack()
mainloop()

With an array of widgets, you put them in a list

from tkinter import *
master = Tk()
scales=list()
Nscales=10
for i in range(Nscales):
    w=Scale(master, from_=0, to=100) # creates widget
    w.pack(side=RIGHT) # packs widget
    scales.append(w) # stores widget in scales list
def read_scales():
    for i in range(Nscales):
        print("Scale %d has value %d" %(i,scales[i].get()))
b=Button(master,text="Read",command=read_scales) # button to read values
b.pack(side=RIGHT)
mainloop()

I hope that's what you want.

JPG



来源:https://stackoverflow.com/questions/18471886/how-to-create-an-array-of-multiple-tkinter-scale-widgets-with-python

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