I"m writing a GUI in Python for an interface for an microcontroller board which enables the user to select the kind of sensor for each channel to be read using tkinter. Since there are a few of them, I wanted to set them up by a loop. Now the problem is, whenever I choose an option for one widget, the other ones will pick that option, too. Obviously I want to be able to pick a different option for each channel.
import tkinter as tk
import numpy as np
root = tk.Tk()
class Window(tk.Frame):
def __init__(self, root):
self.root = root
tk.Frame.__init__(self, root)
self.root.title("Einstellungen")
self.root.geometry(newGeometry="320x200")
self.pack()
self.bg = tk.Canvas(self.root)
self.bg.pack()
analogChannelsIn = tk.LabelFrame(self.root, text="Input", width=100)
analogChannelsIn.pack()
self.AnaOptions = np.array([[["-None-"], ["K-type Thermocouple"], ["rH Sensor"]] * 7], 'object')
self.AnaOptions = self.AnaOptions.reshape([7, 3])
self.addm = np.array([tk.StringVar()] * 7, 'object')
self.acdd = np.zeros(7, 'object')
for i in range(0, 7, 1):
self.acdd[i] = tk.OptionMenu(analogChannelsIn, self.addm[i],*self.AnaOptions[i])
self.addm[i].set("-None-")
self.acdd[i].pack()
settings = Window(root)
settings.mainloop()
The issue is the line:
self.addm = np.array([tk.StringVar()] * 7, 'object')
because [tk.StringVar()] * 7
creates a list of 7 times the same StringVar
. To get 7 different StringVar
, use
self.addm = np.array([tk.StringVar() for i in range(7)], 'object')
instead.