Search code examples
pythonclasstkinterself

How to use class and self here to get two different entries?


With my current code, it does not matter whether I click on "Input Folder" - Change or "JukeBox" change the result always gets displayed in "JukeBox" entry. This is incorrect, using class and self how can I change the code to display result from "Input Folder" - Change in "Input Folder" entry and the result from "Jukbox" - Change in "Jukebox" entry?

Also, how can I save the selected folders to a file so that it is there on app exit and re open?

My code:

import os
from tkinter import *
from tkinter import filedialog

inPut_dir = ''
jukeBox_dir = ''

def inPut():
    opendir = filedialog.askdirectory(parent=root,initialdir="/",title='Input Folder')
    inPut_dir = StringVar()
    inPut_dir = os.path.abspath(opendir)
    entry.delete(0, END)
    entry.insert(0, inPut_dir)

def jukeBox():
    opendir = filedialog.askdirectory(parent=root,initialdir="/",title='JukeBox')
    jukeBox_dir = StringVar()
    jukeBox_dir = os.path.abspath(opendir)
    entry.delete(0, END)
    entry.insert(0, jukeBox_dir)    

root = Tk()
root.geometry("640x240")
root.title("Settings")

frametop = Frame(root)
framebottom = Frame(root)
frameright = Frame(framebottom)

text = Label(frametop, text="Input Folder").grid(row=5, column=2)
entry = Entry(frametop, width=50, textvariable=inPut_dir)
entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)
text = Label(frametop, text="JukeBox").grid(row=6, column=2)
entry = Entry(frametop, width=50, textvariable=jukeBox_dir)
entry.grid(row=6,column=4,padx=2,pady=2,sticky='we',columnspan=20)

ButtonA = Button(frametop, text="Change", command=inPut).grid(row=5, column=28)
ButtonB = Button(frametop, text="Change", command=jukeBox).grid(row=6, column=28)
ButtonC = Button(frameright, text="OK").grid(row=5, column=20, padx=10)
ButtonD = Button(frameright, text="Cancel").grid(row=5, column=15)

frametop.pack(side=TOP, fill=BOTH, expand=1)
framebottom.pack(side=BOTTOM, fill=BOTH, expand=1)
frameright.pack(side=RIGHT)

root.mainloop()

See attached image:enter image description here


Solution

  • Your code has both:

    entry = Entry(frametop, width=50, textvariable=inPut_dir)
    entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)
    

    and

    entry = Entry(frametop, width=50, textvariable=jukeBox_dir)
    entry.grid(row=6,column=4,padx=2,pady=2,sticky='we',columnspan=20)
    

    with jukeBox_dir/row 6 overriding inPut_dir/row 5

    Therefore, in def input: where you have:

    entry.insert(0, inPut_dir)
    

    You'll get the result in row 5 (jukebox_dir)