Hi fellow Tkinter enthusiasts. I'm creating an interface for research purposes. I would like to build an window which displays several slider questions. I was able to create these dynamically with the following code.
The problem I now run into is that each slider object has the same name, and therefor it is not possible to use the SliderQ.get() function. I tried naming each of the sliders after the elements in the dictionary (Q_1 , Q_2 etc) , but unsuccessfully.
How can I retrieve the values of each slider and save them for example in a list, or in the dictionary.
from tkinter import *
from customtkinter import *
root = CTk()
root.geometry("400x500")
SlideAsk = {"Q_1":"This is my question 1.",
"Q_2":"This is my question 2.",
"Q_3":"This is my question 3.",
"Q_4":"This is my question 4."}
startrow = 0
startcol = 1
def CreateSlider(SlideAsk):
global startrow,startcol
for q in SlideAsk:
label_Question = CTkLabel(master=root,text= SlideAsk[q])
label_Question.grid(row=startrow, column=0, columnspan=1, pady=10, padx=10, sticky="w")
startrow =1
SliderQ = CTkSlider(master=root,from_=1,to=5,number_of_steps=4)
SliderQ.grid(row=startrow, column=0, columnspan=2, pady=10, padx=20, sticky="w")
startrow =1
CreateSlider(SlideAsk)
root.mainloop()
CodePudding user response:
I recommend you to use Python classes, as it will be easier to manipulate GUI elements.
As for your problem, putting sliders in a list (while in a for loop) will allow you to use them later:
#!/usr/bin/python3
import tkinter as tk
SlideAsk = {"Q_1":"This is my question 1.",
"Q_2":"This is my question 2.",
"Q_3":"This is my question 3.",
"Q_4":"This is my question 4."}
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.wm_geometry("400x500")
# button to show sliders values
self.del_button = tk.Button(self, text="display", command=self.display_sliders)
self.del_button.grid(row=0,column=3)
# label to show sliders values
self.status_text=tk.StringVar(self)
self.status = tk.Label(self, textvariable=self.status_text)
self.status.grid(row=1,column=3)
# sliders
self.sliders_list=[]
startrow = 0
startcol = 1
simple_cpt = 0
for q in SlideAsk:
label_Question = tk.Label(text= SlideAsk[q])
label_Question.grid(row=startrow, column=0, columnspan=1, pady=10, padx=10, sticky="w")
startrow =1
self.sliders_list.append(tk.Scale(self, from_=1,to=5))
self.sliders_list[simple_cpt].grid(row=startrow, column=0, columnspan=2, pady=10, padx=20, sticky="w")
simple_cpt = 1
startrow =1
def display_sliders(self):
text=""
for i in range(len(self.sliders_list)):
text =list(SlideAsk.keys())[i] " : " str(self.sliders_list[i].get()) " | "
self.status_text.set(text)
if __name__=="__main__":
app = SampleApp()
app.mainloop()
The list containing the sliders is sliders_list, it is used when clicking on the button display. For each slider in the list we get its value, and display it in the label.