Issue In Accessing Elements In Array Of Option Menu Created In Python Tkinter
I created options menu in run time based on user inputs. import tkinter import tkinter.messagebox from tkinter import * top = tkinter.Tk() number_of_pd = Label(top, text='Number o
Solution 1:
OptionMenu
executes function with one agument - selected value - so you have to use lambda
with two arguments
command=lambda val, n=num:new_number_of_pds(val, n))
First is selected value, second will be optionmenu's number "num".
And then function has to get two arguments
defnew_number_of_pds(value, optionmenu_number):
I don't know what you try to do with those elements but if you want to replace item in list then maybe you should create list with 5 empty elements which you can replace with values.
optionmenu number: 0value: 3
a: ['3', None, None, None, None]
-----
optionmenu number: 2value: 5
a: ['3', None, '5', None, None]
-----
Code
import tkinter as tk
# --- functions ---defnew_number_of_pds(value, optionmenu_number):
print('optionmenu number:', optionmenu_number)
print('value:', value)
a[optionmenu_number] = value
print('a:', a)
print('-----')
defnew_number_of_pd(oE_number_of_pd):
global a
# delete previous values
a = [None, None, None, None, None]
for num inrange(int(oE_number_of_pd)):
E_Name[num] = tk.OptionMenu(top, b[num], *list2, command=lambda val, n=num:new_number_of_pds(val, n))
E_Name[num].pack(side="left")
# --- main ---
list2 = ['1', '2', '3', '4', '5']
E_Name=[None, None, None, None, None]
a = [None, None, None, None, None]
top = tk.Tk()
b = [tk.StringVar(), tk.StringVar(), tk.StringVar(), tk.StringVar(), tk.StringVar()]
number_of_pd = tk.Label(top, text="Number of Products")
number_of_pd.pack(side="left")
oE_number_of_pd = tk.StringVar()
E_number_of_pd = tk.OptionMenu(top, oE_number_of_pd, *list2, command=new_number_of_pd)
E_number_of_pd.pack(side="left")
top.mainloop()
Post a Comment for "Issue In Accessing Elements In Array Of Option Menu Created In Python Tkinter"