I'm stuck. I have 15 labels, 15 data entry widgets and 15 browse buttons created in a loop.
When the user clicks on one of the browse buttons, I would like to update the corresponding data entry widget with either the directory name, or filename. Everything is working okay with the exception of the buttons. Whenever I select the directory or filename from any of the button widgets, only the last data entry gets populated, never the corresponding widget.
The code should work as described. The problem is that selecting either of the 1st 2 browse buttons will only update the last data entry widget, not the widget next to the button.
(The computer I'm using doesn't have network connectivity, so I had to type it into my phone's tiny screen).
import sys, os, shuttle, time
from tkinter import *
from tkinter import ttk
from tkinter import filedialog as fd
class MyClass:
def __init__(self, root):
#title
root.title('My Title' )
#mainframe
mainframe = ttk.Frame(root, padding='1 3 12 12')
mainframe.grid(column=0,row=0, sticky=(N,W,E,S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
#Setup notebook
Mytab=ttk.Notebook(mainframe)
Mytab.grid(column=0,row=0, sticky=(N,W,E,S))
#SET Frames for each tab
SettingsFrame=ttk.Frame( Mytab,padding='1 1 12 12')
SettingsFrame.grid( column=3, row=20, sticky=(N,W,E,S))
#Add frames
Mytab.add(SettingsFrame, text='Dir paths')
#List vars for labels, dir, files, & cmd
TheLabels = ['Dir1', 'File1', 'Dir2']
TheDataEntry = ['D:/Dir1','D:/DirX/Filename1','D:/Dir2']
TheCmds = ['Open_folder','Open_file','Open_folder']
ttk.Label(SettingsFrame, text='Default DIR names: ').grid(column=1, row=1, sticky=W)
self.PHBrowseOpen = PhotoImage( file = r'C:\pic\mypic.png' )
myindex=2
i=0
self.mystringVars = []
self.myEntries = []
self.myButtons = []
for labs, des, cmds in zip(TheLabels, TheDataEntry, TheCmds):
ttk.Label( SettingsFrame, text=labs ).grid( column=1, row=myindex, sticky=W)
self.myvar = StringVar()
self.myvar.set( os.path.normpath(des))
mystringVars.append( self.myvar )
self.entry = ttk.Entry( SettingsFrame, width=72, textvariable=self.myvar )
self.entry.grid(column=2, row=myindex, sticky=(W,E))
self.myEntries.append(self.entry)
if cmds == 'Open_folder':
self.myButton.append( ttk.Button( SettingsFrame, text='Browse', image=self.PHBrowseOpen, command=lambda i=i: self.Open_folder(i)))
else:
self.myButton.append( ttk.Button( SettingsFrame, text='Browse', image=self.PHBrowseOpen, command=lambda i=i: self.Open_txt_file(i)))
self.myButton[i].grid( column=3, row=myindex, sticky=E)
myindex +=1
i+=1
#open folder
def Open_folder( self, myNum ):
d = os.path.normpath( fd.askdirectory() )
for i in range( len( self.myentries )):
if i== myNum:
self.myvar.set( os.path.normpath(d) )
#open file
def Open_file( self, myNum ):
typefaces = (('text', '*.txt'),('JPEG','*.jpg'))
d = os.path.normpath( f.askopenfilename(filetypes=typefiles) )
for i in range( len( self.myentries )):
if i== myNum:
self.myvar.set( os.path.normpath(f) )