Reputation: 67
I would like to create a function or class that has the proper formatting to create a text label, entry field, and button. The button would allow me to browse through my directory and populate the entry field with the chosen directory. The code I have allows me to do most of this, however the directory is always populated in the last entry field instead of the one the button refers to.
I am new to tkinter and GUIs so apologies if this is a simple solution, I assume the problem is with root.name.set
referring to the function that was called last.
from tkinter import *
from tkinter import filedialog
def askdirectory():
dirname = filedialog.askdirectory()
root.name.set(dirname)
def dirField(root, label, rowNum):
text = StringVar()
text.set(label)
dirText = Label(root, textvariable = text, height =4)
dirText.grid(row = rowNum, column = 1)
dirBut = Button(root, text = 'Browse', command = askdirectory)
dirBut.grid(row = rowNum, column = 3)
root.name = StringVar()
adDir = Entry(root,textvariable = root.name, width = 100)
adDir.grid(row = rowNum, column = 2)
if __name__ == '__main__':
root = Tk()
root.geometry('1000x750')
adText = "Select directory of Ads"
userText = "Select directory of User credentials"
adField = dirField(root, adText, 1)
userField = dirField(root, userText, 2)
root.mainloop()
Upvotes: 0
Views: 46
Reputation: 4407
You should realise that you need to have each Entry
have its own textvariable
. Otherwise they will overlap. Have a look at my code, which should get you going.
from tkinter import *
from tkinter import filedialog
path = [None, None] # Fill it with the required number of filedialogs
def askdirectory(i):
dirname = filedialog.askdirectory()
path[i].set(dirname)
def dirField(root, label, rowNum, i):
dirText = Label(root, text=label)
dirText.grid(row=rowNum, column=0)
dirBut = Button(root, text='Browse', command=lambda: askdirectory(i))
dirBut.grid(row=rowNum, column=2)
path[i] = StringVar()
adDir = Entry(root, textvariable=path[i], width=50)
adDir.grid(row=rowNum, column=1)
if __name__ == '__main__':
root = Tk()
adText = "Select directory of Ads"
userText = "Select directory of User credentials"
adField = dirField(root, adText, 0, 0)
userField = dirField(root, userText, 1, 1)
root.mainloop()
Upvotes: 1