0

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.

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your quick response.Will try it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.