I'm trying to devise a tkinter gui, that, among others, lets users choose a 'working folder' and a 'destination folder (and there is more coming). I stripped the code to its bare functionality hereunder.
I found myself duplicating code for the selection of both the 'working folder' and the 'destination' folder. I came up with the solution to put these variables in a dictionary (I could pass them as mutable objects along with the lambda). Although it is a working solution, I have the feeling there is more standard way of achieving this objective.
My question therefore is: how can I make my _browsefile()
function work whilst changing the value of self.working_dir
and self.destination_dir
, without using an artificial dictionary structure, hence avoiding duplicate code? This would implicate that I can generalize the _browsefile
func somehow.
I have seen very advanced reusage features in text books, but currently this is out of my league. If I can learn to tackle this 'easy' one, it would possibly help me on my journey.
Thank you for giving me advice in doing it the Pythonic way...
import tkinter as tk
from tkinter import filedialog
class View():
def __init__(self, parent):
self.parent = parent
self.gui_variables = {'working dir': '',
'destination dir': ''}
self.menu()
def menu(self):
self.folder_button1 = tk.Button(self.parent, text="Choose Working Folder",
command=lambda: self._browsefile(self.gui_variables['working dir']))
self.folder_button1.pack()
self.folder_button2 = tk.Button(self.parent, text="Choose Dest. Folder",
command=lambda: self._browsefile(self.gui_variables['destination dir']))
self.folder_button2.pack()
def _browsefile(self, directory):
answer = tk.filedialog.askdirectory()
self.gui_variables[directory] = answer
if __name__ == '__main__':
root = tk.Tk()
View(root)
root.mainloop()