Related
I've been coding a program that would let you practice multiplication, on the program, I've made it so the user can select what numbers they want to practice with checkboxes. I've managed to get it working but I was wondering if there is a more iterative way of doing it since i want to go from 1 to 12. I've seen ways of making checkboxes from a list but I haven't been able to get it to work.
from msilib.schema import CheckBox
from tkinter import *
import random
from tkinter import messagebox
class Timestable:
def __init__(self, parent):
self.f1 = Frame(parent)
self.f1.grid()
self.f2 = Frame(parent)
self.f2.grid()
self.f2.grid_forget()
self.f3 = Frame(parent)
self.f3.grid()
self.f3.grid_forget()
#frame 1 ========================================================
Label(self.f1,text="Multiplication Practice").grid()
Label(self.f1,text="Name:").grid()
self.name = Entry (self.f1)
self.name.grid()
Label(self.f1,text="Age").grid()
self.age = Entry (self.f1)
self.age.grid()
self.user = []
self.incorrect=[]
self.checked1 = IntVar()
self.checked2 = IntVar()
self.c1 = Checkbutton(self.f1, text='1',variable=self.checked1,onvalue=1,offvalue=0,command=self.save)
self.c1.grid()
self.c2 = Checkbutton(self.f1, text='2', variable=self.checked2,onvalue=1,offvalue=0,command=self.save)
self.c2.grid()
self.w = Spinbox(self.f1, from_=1, to=5)
self.w.grid()
Button(self.f1,text="Start", command=self.start).grid()
#frame 2 ========================================================
Label(self.f2,text="Frame 2 ").grid()
self.x=0
self.correct=0
sub = lambda: Timestable.Submit(self)
Button(self.f2,text="submit", command=sub).grid()
self.entryWidget = Entry (self.f2)
self.entryWidget.grid()
#frame 3 ========================================================
Label(self.f3,text="Frame 3 ").grid()
# ===============================================================
def save(self):
if self.checked1.get() == 1:
self.user.append(1)
if self.checked2.get() == 1:
self.user.append(2)
#self.user.append(self.checked1.get())
def clear_text(self):
self.entryWidget.delete(0, 'end')
def Questions(self):
number1 = random.choice(self.user)
number2 = random.randrange(1,12)
self.answer = number1 * number2
self.prompt = (str(number1) + " X " + str(number2))
quest = Label(self.f2, text=self.prompt, width=len(self.prompt))
quest.grid()
return self.answer
def start(self):
self.f1.grid_forget()
self.f2.grid()
self.Questions()
def results(self):
self.f2.grid_forget()
self.f3.grid()
def Submit(self):
if self.entryWidget.get() == "":
messagebox.showerror("Error", "Please enter a number.")
elif self.entryWidget.get() == str:
messagebox.showerror("Error", "Please enter a number, not letters.")
else:
if self.answer != int(self.entryWidget.get().strip()):
messagebox.showinfo("Answer", "INCORRECT! Answer: " + str(self.answer))
self.incorrect.append(self.prompt)
else:
messagebox.showinfo("Answer", "CORRECT!")
self.correct = self.correct +1
self.x=self.x+1
if self.x < int(self.w.get()):
self.Questions()
self.clear_text()
else:
self.results()
self.percent = round(self.correct/self.x*100)
Label(self.f3,text="Congrats, you got "+ str(self.percent) +"% of the questions correct" ).grid()
Label(self.f3,text = self.incorrect).grid()
root = Tk()
root.geometry("200x300")
Timestable(root)
root.mainloop()
Instead of creating the checkboxes one by one, you can use a for loop to create them:
class Timestable:
def __init__(self, parent):
...
self.user = []
self.incorrect = []
# -- create those checkboxes
# list to store the tkinter variables for those checkboxes
self.checked = []
# suggest to create those checkboxes inside a frame
# and put 3 checkboxes in a row
frame = Frame(self.f1)
frame.grid()
for i in range(12):
self.checked.append(IntVar()) # store the tkinter variable for the checkbox
Checkbutton(frame, text=i+1, variable=self.checked[-1], onvalue=i+1, offvalue=0, anchor='w').grid(row=i//3, column=i%3, sticky='ew')
...
Note that I don't require the save(). You can build the self.user inside start():
def start(self):
# get the user selected numbers
self.user = [v.get() for v in self.checked if v.get()]
# you can check the user list
#print(self.user)
if self.user:
# only start the game when there are numbers selected
self.f1.grid_forget()
self.f2.grid()
self.Questions()
I am using Tkinter/Python to get the selected option on the window when the button is pressed. On clicking the button - only the value from list should get printed. As of now, it's printing any value typed into combobox. Any help/suggestion will be appreciated.
from tkinter import *
from tkinter import ttk
class Run:
def __init__(self, master):
self.lst = ["Apples", "Oranges", "Pears", "Grapes"]
self.master = master
self.toplevels = 0
master.title("CB")
master.geometry("300x200")
label = Label(master, text = "ABC")
label.pack()
self.combo_box = ttk.Combobox(master,value=self.lst)
self.combo_box.set('')
self.combo_box.pack()
self.combo_box.bind('<KeyRelease>', self.search)
button = Button(master, text="btn", command=self.make_new)#self.make_new)
button.pack()
def make_new(self):
if not self.toplevels:
#new = tk.Toplevel(self.master)
my_label = Label(self.master, text=self.combo_box.get(), font=("Helvetica", 14))#, fg="grey")
my_label.pack(padx=10, pady=10)
self.toplevels += 1
def search(self, event):
value = event.widget.get()
if value == '':
self.combo_box['values'] = self.lst
else:
data = []
for item in self.lst:
if value.lower() in item.lower():
data.append(item)
self.combo_box['values'] = data
master1 = Tk()
i = Run(master1)
master1.mainloop()
The answer is simple. You just have to a condition which will detect if the text of the combo box is in the list or not. That condition would be: if self.combo_box.get() in self.lst:. And for the corrected code:
from tkinter import *
from tkinter import ttk
class Run:
def __init__(self, master):
self.my_label = Label(master, text="")
self.lst = ["Apples", "Oranges", "Pears", "Grapes"]
self.master = master
self.toplevels = 0
master.title("CB")
master.geometry("300x200")
label = Label(master, text="ABC")
label.pack()
self.combo_box = ttk.Combobox(master, value=self.lst)
self.combo_box.set('')
self.combo_box.pack()
self.combo_box.bind('<KeyRelease>', self.search)
button = Button(master, text="btn", command=self.make_new) # self.make_new)
button.pack()
def make_new(self):
if not self.toplevels:
# new = tk.Toplevel(self.master)
if self.combo_box.get() in self.lst:
self.my_label.config(text=self.combo_box.get(), font=("Helvetica", 14)) # , fg="grey")
self.my_label.pack(padx=10, pady=10)
self.toplevels += 1
def search(self, event):
value = event.widget.get()
if value == '':
self.combo_box['values'] = self.lst
else:
data = []
for item in self.lst:
if value.lower() in item.lower():
data.append(item)
self.combo_box['values'] = data
master1 = Tk()
i = Run(master1)
master1.mainloop()
Hope this helps
I'm trying to create a tkinter widget that takes nested dictionaries as input and generates OptionMenus that continue to narrow down choices until the choice dictionaries culminate in a value.
So far, the widgets generate correctly, but are not destroyed correctly. I've currently removed widget regeneration based off changing choices as it would cause more and more widgets to appear each time a change was made.
Here is the code, as it wasn't pasting here nicely.
import tkinter as tk
labelwidth = 20
inputwidth = 25
class DropDownWidget(tk.Frame):
def __init__(self, parent, labeltext, optionType, options, command=""):
if not isinstance(options, dict):
print(options)
raise TypeError("DropDownWidgets take dictionaries of the choices and the values they represent as keys and values")
tk.Frame.__init__(self, parent)
self.optionType = optionType
self.options = options
self.optionKeys = list(options.keys())
self.optionValues = list(options.values())
self.dropDownDisplayed = tk.StringVar(self, self.optionKeys[0])
self.label = tk.Label(self, text=labeltext, width=labelwidth, justify="left", relief="groove", anchor="w")
self.input = tk.OptionMenu(self, self.dropDownDisplayed, *list(options.keys()), command=command) # , command=self.updateValue)
self.input.config(width=inputwidth-7)
self.label.grid(row=0, column=0)
self.input.grid(row=0, column=1)
def updateValue(self, something):
self.inputVar.set(self.options[self.dropDownDisplayed.get()])
def replaceOptionMenu(self, options, command, *args):
self.options = options
self.input.grid_forget()
self.dropDownDisplayed.set(list(options.keys())[0])
self.input = tk.OptionMenu(self, self.dropDownDisplayed, *list(options.keys()), command=command)
self.input.config(width=inputwidth - 7)
self.input.grid(row=0, column=2)
def replaceOptionMenuNoCmd(self, options):
self.options = options
self.input.grid_forget()
self.dropDownDisplayed.set(list(options.keys())[0])
self.input = tk.OptionMenu(self, self.dropDownDisplayed, *list(options.keys()))
self.input.config(width=inputwidth - 7)
self.input.grid(row=0, column=2)
def value(self):
return self.optionType(self.options[self.dropDownDisplayed.get()])
def setValue(self, value):
self.dropDownDisplayed.set(value)
class MultiDropDownWidget(tk.Frame):
def __init__(self, parent, options, isChild=False):
tk.Frame.__init__(self, parent, relief="raised", bg="blue")
self.originalOptions = options
if isChild is False:
self.root = self
else:
self.root = parent.root
if isinstance(options, dict):
if isinstance(list(options.values())[0], dict):
self.options = {key: key for key in options.keys()}
self.hasChild = True
else:
self.options = {key: value for key, value in options.items()}
self.hasChild = False
#
else:
self.options = options
if self.hasChild:
self.dropDown = DropDownWidget(self.root, "Choice", str, self.options,
command=lambda x: self.destroyChildren()) # self.updateChild)
else:
self.dropDown = DropDownWidget(self.root, "Choice", str, self.options)
self.dropDown.pack()
if self.hasChild:
self.child = MultiDropDownWidget(self.root, options[self.dropDown.value()], isChild=True)
else:
pass
def updateChild(self, *args):
if self.hasChild:
self.child.destroyChildren()
self.child = MultiDropDownWidget(self, self.originalOptions[self.dropDown.value()], isChild=True)
def destroyChildren(self, *args):
if self.hasChild:
self.child.destroyChildren()
self.child.destroy()
if not self.hasChild:
self.destroy()
options = {'a': {
'aa': {'aaa': 'aaa'},
'ab': {'aba': 'aba'},
},
'b': {
'bb': {'bbb': 'bbb'},
'bc': {'bcc': 'bcc'},
},
'c':
{'c1': {'c2': 'c2'}}}
root = tk.Tk()
multiWidget = MultiDropDownWidget(root, options)
multiWidget.pack()
root.mainloop()
The problem seems to lie within destroyChildren()
I can see that the destroy()s are being called on the correct objects when using the debugger, but they are lingering around for some reason. I have also noticed that if I destroy the root widget they will all be destroyed, as expected.
I am also able to destroy their inner DropDownWidget without issue, but their empty frame and the MultiDropDownWidget still exist.
I tried making the MultiDropDown Frame.init make the frame show a blue background, but I'm not seeing the blue show up anywhere, which is probably where the issue lies. I'm still not sure why a component is resisting being destroyed.
If you replace the dropDown command with when hasChild is True with updateChildren you'll see the new children be generated without the old children being destroyed.
I have restructured the widgets not to be their own MultiDropDownWidget objects but DropDownWidget objects that are stored in a list of the MultiDropDownWidget. Two issues that it has which should be okay for my use are that if a top-level key leads directly to a value, it crashes, and sub-options can't have the same value as an option preceding it when it is changed or it will reconfigure improperly.
class MultiDropDownWidget(tk.Frame):
def __init__(self, parent, options, isChild=False):
tk.Frame.__init__(self, parent, relief="raised", bg="blue")
self.originalOptions = options
if isChild is False:
self.root = self
else:
self.root = self
if isinstance(options, dict):
if isinstance(list(options.values())[0], dict):
self.options = {key: key for key in options.keys()}
self.hasChild = True
else:
self.options = {key: value for key, value in options.items()}
self.hasChild = False
else:
raise TypeError("DropDownWidgets take dictionaries of the choices and the values they represent as keys and values")
self.widgets = []
self.widgetValues = []
self.valueLabel = FreeInputWidget(self, "Value", str)
self.baseChoice = self.dropDown = DropDownWidget(self.root, "Choice", str, self.options,
command=lambda x: self.reconstructChildren(x))
self.widgets.append(self.baseChoice)
self.baseChoice.pack()
self.constructChildren(oOptions=self.originalOptions[self.baseChoice.value()])
self.valueLabel.pack()
#disableInput(self.valueLabel)
def constructChildren(self, *args, oOptions="", widgetList=""):
options = oOptions
while True:
b = False
if isinstance(options, dict):
if isinstance(list(options.values())[0], dict):
childoptions = {key: key for key in options.keys()}
command = self.reconstructChildren
child = DropDownWidget(self.root, "Choice", str, childoptions, command=lambda x: self.reconstructChildren(x))
self.root.widgets.append(child)
child.pack()
options = options[child.value()]
else:
b = True
childoptions = {key: value for key, value in options.items()}
child = DropDownWidget(self.root, "Choice", str, childoptions, command=self.updateValueLabel)
self.root.widgets.append(child)
child.pack()
else:
pass
# child = DropDownWidget(self.root, "Choice", str, childoptions, command=command)
# self.root.widgets.append(child)
# child.pack()
if b is True:
break
else:
pass
# options = options[child.value()]
self.updateValueLabel()
def updateValueLabel(self, *args):
self.valueLabel.setValue(self.widgets[len(self.widgets)-1].value())
self.valueLabel.pack_forget()
self.valueLabel.pack()
def destroyChildren(self, index, *args):
for child in self.widgets[index:]:
# print(f"{child.value()} destroyed")
child.pack_forget()
self.widgets.pop(self.widgets.index(child))
child.destroy()
def reconstructChildren(self, x, *args):
# print(self.widgets)
i = 0
for widget in self.widgets:
# print(x, widget.value())
if x == widget.value():
break
i += 1
# print(x)
# print(i)
self.destroyChildren(i+1)
newOptions = self.getDictLayer(i)#self.originalOptions, i, keyy)[keyy] #[keyy]
self.constructChildren(oOptions=newOptions) #self.widgets[i].originalOptions)
def getDictLayer(self, index, *args):
options = self.originalOptions
if index == 0:
return options[self.baseChoice.value()]
for i in range(0, index+1):
# print(self.widgets[i].value())
options = options[self.widgets[i].value()]
return options
Using this list I want to be able to get two inputs. That will be stored in variables. Any suggestions?? Please help I am new to tkinter.
import tkinter as tk
class App():
def __init__(self, master):
self.master = master
self.type_integration = None
self.typeChoice = tk.StringVar()
self.typeChoice.set(None) # This fixes the grayness of the radio buttons!
self.typeFrame = tk.Frame(master)
OPTIONS = [('Arsenal','Arsenal'),('Aston Villa','Aston Villa'),('Burnley','Burnley'),('Chelsea','Chelsea'),('Crystal Palace','Crystal Palace'),('Everton','Everton'),('Hull','Hull'),('Leicester','Leicester',),('Liverpool','Liverpool'),('Manchester City','Manchester City'),('Manchester United','Manchester United'),('Newcastle United','Newcastle United'),('Queens Park Rangers','Queens Park Rangers'),('Southampton','Southampton'),('Stoke','Stoke'),('Sunderland','Sunderland'),('Swansea','Swansea'),('Tottenham','Tottenham'),('West Bromwich Albion','West Bromwich Albion'), ('West Ham','West Ham')]
for text, value in OPTIONS:
tk.Radiobutton(self.typeFrame, text=text, variable=self.typeChoice, value=value).pack(anchor = 'w')
tk.Button(self.typeFrame, text="Confirm Home Team", command=self.exit).pack(anchor = 'w')
self.typeFrame.pack()
def exit(self):
self.type_integration = self.typeChoice.get()
self.master.destroy()
def getinput(self):
return self.type_integration
master = tk.Tk()
app = App(master)
tk.mainloop()
home = app.getinput()
print(home)
Do I need to make another class?? Or can I reuse the code?? Help would be much appreciated. Am willing to listen to anything as I am not very good.
RadioButton is a Tkinter widget used to implement one-of-many selections.
You need to use CheckButton widget instead to do what you want.
def __init__(self, master):
...
self.variables = variables = []
for text, value in OPTIONS:
var = tk.StringVar()
variables.append(var)
tk.Checkbutton(self.typeFrame, text=text, variable=var,
onvalue=text, offvalue='').pack(anchor = 'w')
...
def exit(self):
self.type_integration = ','.join(v.get() for v in self.variables if v.get())
self.master.destroy()
UPDATE
To limit at most 2 selection:
def __init__(self, master):
...
self.variables = []
self.checkboxs = []
for text, value in OPTIONS:
var = tk.StringVar()
cb = tk.Checkbutton(self.typeFrame, text=text, variable=var,
onvalue=text, offvalue='', command=self.limit2)
cb.pack(anchor = 'w')
self.variables.append(var)
self.checkboxs.append(cb)
...
def limit2(self):
if sum(bool(v.get()) for v in self.variables) >= 2:
# Disable non-selected items to limit selection
for cb, v in zip(self.checkboxs, self.variables):
if not v.get():
cb['state'] = 'disabled'
else:
for cb in self.checkboxs:
cb['state'] = 'normal'
It is two weeks now that I full-time look for a solution to a relevant problem: How to create Commands within dynamic loops? The subject is simple (to image it I took food elements): to initiate the programme, I have a number of packs to determine (for instance 5, then press Enter). Then thanks to created Comboboxes, for each case, specify whether it is fruits, vegetable, or other. The aim of each Combobox is to create again a Widget proper to value executed. The problem is that when Bind is executed, loops works for the whole sequence and duplicate anterior widget. the problem may be resolved by adding an instruction at line 48 such as:
if 'Selection'.get() == self.Combo_Food_liste[i]:
but I look for 'Selection' meaning Object I cannot reach it! Or if you have a better Idea, I would be very pleased to know it!
Thank you!!
from ttk import *
from Tkinter import *
class Postproc:
def __init__(self, parent, title):
self.variable_Title_Frame = []
self.variable_Title =[]
self.Combo_Food_Select=[]
self.Combo_Food_stock=[]
self.Combo_Food_liste=[]
self.Combo_Food_Pos_Select={}
self.Combo_Food_Pos_stock={}
self.Combo_Food_Pos_liste={}
self.Combo_Food_Pos_Entry={}
self.parent = parent
self.parent.title(title)
self.parent.protocol("WM_DELETE_WINDOW", self.Closes)
Frame1 = Frame(self.parent,borderwidth=.5,relief=GROOVE)
Frame1.pack(side=LEFT,padx=1,pady=1)
### Define the number of packs then press 'Enter'
self.variables_Title_number=IntVar()
self.Field_Ouputs = Entry(Frame1, textvariable=self.variables_Title_number, bg ='bisque', fg='maroon')
self.Field_Ouputs.pack(side=LEFT,padx=1,pady=1)
self.Field_Ouputs.bind("<Return>", self.Launch_Outputs)
def Closes(self, event=None):
self.parent.destroy()
def Launch_Outputs(self, event=None):
self.Nombr = self.variables_Title_number.get()
self.Create_Outputs(self.Nombr)
def Create_Outputs(self, Nombr):
#### Define for each pack the kind of food
for i in range (0,Nombr):
self.variable_Title_Frame.append(Frame(MainWin,borderwidth=.5,relief=GROOVE))
self.variable_Title_Frame[i].pack(side= LEFT,expand=YES)
Label(self.variable_Title_Frame[i],text=i).pack(padx=1,pady=1)
self.Combo_Food_Select.append(StringVar())
self.Combo_Food_stock.append(('Fruit', 'Vegetable', 'Other'))
self.Combo_Food_liste.append(Combobox(self.variable_Title_Frame[i], textvariable = self.Combo_Food_Select[i], \
values = self.Combo_Food_stock[i], state = 'readonly'))
self.Combo_Food_liste[i].bind("<<ComboboxSelected>>", self.Position_Magnitude)
self.Combo_Food_liste[i].pack()
def Position_Magnitude(self, index):
##### Define for each kind the variety
for i in range (0, self.Nombr):
if self.Combo_Food_liste[i].get() == 'Fruit':
self.Combo_Food_Pos_Select[i]=(StringVar())
self.Combo_Food_Pos_stock[i]=(['Apple', 'Orange'])
self.Combo_Food_Pos_liste[i]=(Combobox(self.variable_Title_Frame[i], textvariable = self.Combo_Food_Pos_Select[i], \
values = self.Combo_Food_Pos_stock[i], state = 'readonly'))
self.Combo_Food_Pos_liste[i].pack(side=BOTTOM)
if self.Combo_Food_liste[i].get() == 'Vegetable':
self.Combo_Food_Pos_Select[i]=(StringVar())
self.Combo_Food_Pos_stock[i]=(['Tomatoe', 'Pepper', 'Peas'])
self.Combo_Food_Pos_liste[i]=(Combobox(self.variable_Title_Frame[i], textvariable = self.Combo_Food_Pos_Select[i], \
values = self.Combo_Food_Pos_stock[i], state = 'readonly'))
self.Combo_Food_Pos_liste[i].pack(side=BOTTOM)
if self.Combo_Food_liste[i].get() == 'Other':
self.Combo_Food_Pos_Select[i]=(StringVar())
self.Combo_Food_Pos_Entry[i]=Entry(self.variable_Title_Frame[i], textvariable=self.Combo_Food_Pos_Select[i], bg ='bisque', fg='maroon')
self.Combo_Food_Pos_Select[i].set("Specify")
self.Combo_Food_Pos_Entry[i].pack(side=BOTTOM)
if self.Combo_Food_liste[i].get() == "":
next
if __name__ == '__main__':
MainWin = Tk()
app = Postproc(MainWin, "Main Window")
MainWin.mainloop()
You can use lambda function to send i to Position_Magnitude()
self.Combo_Food_liste[i].bind("<<ComboboxSelected>>", lambda event, index=i:self.Position_Magnitude(event,index))
In Position_Magnitude you can use event.widget in place of self.Combo_Food_liste[i]
from ttk import *
from Tkinter import *
class Postproc:
def __init__(self, parent, title):
self.variable_Title_Frame = []
self.variable_Title =[]
self.Combo_Food_Select=[]
self.Combo_Food_stock=[]
self.Combo_Food_liste=[]
self.Combo_Food_Pos_Select={}
self.Combo_Food_Pos_stock={}
self.Combo_Food_Pos_liste={}
self.Combo_Food_Pos_Entry={}
self.parent = parent
self.parent.title(title)
self.parent.protocol("WM_DELETE_WINDOW", self.Closes)
Frame1 = Frame(self.parent,borderwidth=.5,relief=GROOVE)
Frame1.pack(side=LEFT,padx=1,pady=1)
### Define the number of packs then press 'Enter'
self.variables_Title_number=IntVar()
self.Field_Ouputs = Entry(Frame1, textvariable=self.variables_Title_number, bg ='bisque', fg='maroon')
self.Field_Ouputs.pack(side=LEFT,padx=1,pady=1)
self.Field_Ouputs.bind("<Return>", self.Launch_Outputs)
def Closes(self, event=None):
self.parent.destroy()
def Launch_Outputs(self, event=None):
self.Nombr = self.variables_Title_number.get()
self.Create_Outputs(self.Nombr)
def Create_Outputs(self, Nombr):
#### Define for each pack the kind of food
for i in range(Nombr):
self.variable_Title_Frame.append(Frame(MainWin,borderwidth=.5,relief=GROOVE))
self.variable_Title_Frame[i].pack(side= LEFT,expand=YES)
Label(self.variable_Title_Frame[i],text=i).pack(padx=1,pady=1)
self.Combo_Food_Select.append(StringVar())
self.Combo_Food_stock.append(('Fruit', 'Vegetable', 'Other'))
self.Combo_Food_liste.append(Combobox(self.variable_Title_Frame[i], textvariable = self.Combo_Food_Select[i], \
values = self.Combo_Food_stock[i], state = 'readonly'))
self.Combo_Food_liste[i].bind("<<ComboboxSelected>>", lambda event, index=i:self.Position_Magnitude(event,index))
self.Combo_Food_liste[i].pack()
def Position_Magnitude(self, event, index):
#print event.widget, index
if event.widget.get() == 'Fruit':
self.Combo_Food_Pos_Select[index]=(StringVar())
self.Combo_Food_Pos_stock[index]=(['Apple', 'Orange'])
self.Combo_Food_Pos_liste[index]=(Combobox(self.variable_Title_Frame[index], textvariable = self.Combo_Food_Pos_Select[index], \
values = self.Combo_Food_Pos_stock[index], state = 'readonly'))
self.Combo_Food_Pos_liste[index].pack(side=BOTTOM)
if event.widget.get() == 'Vegetable':
self.Combo_Food_Pos_Select[index]=(StringVar())
self.Combo_Food_Pos_stock[index]=(['Tomatoe', 'Pepper', 'Peas'])
self.Combo_Food_Pos_liste[index]=(Combobox(self.variable_Title_Frame[index], textvariable = self.Combo_Food_Pos_Select[index], \
values = self.Combo_Food_Pos_stock[index], state = 'readonly'))
self.Combo_Food_Pos_liste[index].pack(side=BOTTOM)
if event.widget.get() == 'Other':
self.Combo_Food_Pos_Select[index]=(StringVar())
self.Combo_Food_Pos_Entry[index]=Entry(self.variable_Title_Frame[index], textvariable=self.Combo_Food_Pos_Select[index], bg ='bisque', fg='maroon')
self.Combo_Food_Pos_Select[index].set("Specify")
self.Combo_Food_Pos_Entry[index].pack(side=BOTTOM)
if event.widget.get() == "":
next
if __name__ == '__main__':
MainWin = Tk()
app = Postproc(MainWin, "Main Window")
MainWin.mainloop()
EDIT:
by the way: you will have to remove old combobox/entry if you select new thing in top combobox
def Position_Magnitude(self, event, index):
#print event.widget, index
try:
if self.Combo_Food_Pos_liste[index]:
self.Combo_Food_Pos_liste[index].pack_forget()
except:
pass
try:
if self.Combo_Food_Pos_Entry[index]:
self.Combo_Food_Pos_Entry[index].pack_forget()
except:
pass
if event.widget.get() == 'Fruit':
self.Combo_Food_Pos_Select[index]=(StringVar())
self.Combo_Food_Pos_stock[index]=(['Apple', 'Orange'])
self.Combo_Food_Pos_liste[index]=(Combobox(self.variable_Title_Frame[index], textvariable = self.Combo_Food_Pos_Select[index], \
values = self.Combo_Food_Pos_stock[index], state = 'readonly'))
self.Combo_Food_Pos_liste[index].pack(side=BOTTOM)
if event.widget.get() == 'Vegetable':
self.Combo_Food_Pos_Select[index]=(StringVar())
self.Combo_Food_Pos_stock[index]=(['Tomatoe', 'Pepper', 'Peas'])
self.Combo_Food_Pos_liste[index]=(Combobox(self.variable_Title_Frame[index], textvariable = self.Combo_Food_Pos_Select[index], \
values = self.Combo_Food_Pos_stock[index], state = 'readonly'))
self.Combo_Food_Pos_liste[index].pack(side=BOTTOM)
if event.widget.get() == 'Other':
self.Combo_Food_Pos_Select[index]=(StringVar())
self.Combo_Food_Pos_Entry[index]=Entry(self.variable_Title_Frame[index], textvariable=self.Combo_Food_Pos_Select[index], bg ='bisque', fg='maroon')
self.Combo_Food_Pos_Select[index].set("Specify")
self.Combo_Food_Pos_Entry[index].pack(side=BOTTOM)
if event.widget.get() == "":
next