Dynamic Addition of Option Menu tKinter Python

I'm quite new to python. I have a requirement where I have to read a data file and based on the number of records inside the file, I have to create the same number of option menus related to that data. But option menu's options can be fetched from simple list. Please find the code below.

import tkinter as tk
from tkinter import *

root=tk.Tk()
root.title("GridAssign")


Grids=('Grid1','Grid2','Grid3','Grid4','Grid5')
file=open(Datafilepath,"r")
ing=file.read().splitlines()
print (len(ing))

variable = StringVar(root)
variable.set(Grids[0])

for i in range(len(ing)):

  label = tk.Label(root,text=ing[i])
  label.grid(row=i,pady=3,sticky=W)
  w=OptionMenu (root, variable, *tuple(Grids)))
  w.grid(row=i,column=2,pady=3,sticky=E)

root.mainloop()

The above code is able to give me n number of option menus but if I choose one value in one option menu other option menu's value also changes. Can someone please let me know how to achieve this.

Thanks, Santty.

Upvotes: 0

Views: 1026

Answers (1)

MrAlexBailey
MrAlexBailey

Reputation: 5289

This is happening because each of your OptionMenu are using the same StringVar. So naturally when one OptionMenu makes a change to that StringVar, the other menus also reflect that change.

To prevent this you can use a separate StringVar for each menu:

import tkinter as tk
from tkinter import *

root=tk.Tk()
root.title("GridAssign")


Grids=('Grid1','Grid2','Grid3','Grid4','Grid5')
file=open(Datafilepath,"r")
ing=file.read().splitlines()
print (len(ing))

variable_dict = {}

for i in range(len(ing)):
    variable = StringVar(root)
    variable.set(Grids[0])
    variable_dict[i] = variable

    label = tk.Label(root,text=ing[i])
    label.grid(row=i,pady=3,sticky=W)
    w=OptionMenu (root, variable, *tuple(Grids)))
    w.grid(row=i,column=2,pady=3,sticky=E)

root.mainloop()

You can then access each of the StringVars through the dictionary variable_dict

Upvotes: 1

Related Questions