简体   繁体   中英

Tkinter one button changes 2 entries

I'm building a simple application with Tkinter that has two browse buttons. One needs to be able to target a file and the other one only a folder. This works, but when I browse using either one button, it fills both of the entries. I'm new to Tkinter so I don't really understand why.

I'm using code from this question: How to Show File Path with Browse Button in Python / Tkinter

This is my browse function:

def open_file(type):
global content
global file_path
global full_path

if type == "file":
    filename = askopenfilename()
    infile = open(filename, 'r')
    content = infile.read()
    file_path = os.path.dirname(filename)
    entry.delete(0, END)
    entry.insert(0, file_path+filename)
    return content

elif type == "path":
    full_path = askdirectory()
    entry2.delete(0, END)
    entry2.insert(0, full_path)
    #return content

And this is my GUI code:

mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250)
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250)
f2.pack(fill=X)

Label(f1, text="Select Your File (Only txt files)").grid(row=0, column=0, sticky='e')
Label(f2, text="Select target folder").grid(row=0, column=0, sticky='e')
entry = Entry(f1, width=50, textvariable=file_path)
entry2 = Entry(f2, width=50, textvariable=full_path)
entry.grid(row=0, column=1, padx=2, pady=2, sticky='we', columnspan=25)
entry2.grid(row=0, column=1, padx=(67, 2), pady=2, sticky='we', columnspan=25)
Button(f1, text="Browse", command=lambda: open_file("file")).grid(row=0, column=27, sticky='ew', padx=8, pady=4)
Button(f2, text="Browse", command=lambda: open_file("path")).grid(row=0, column=27, sticky='ew', padx=8, pady=4)

How can I solve this problem? Thanks

Notice that the full_path (local variable in open_file method) has the same name as the global varibale.

You should use StringVar for text variables.

Change the initialization of both the file_path and full_path

global file_path
global full_path
file_path = StringVar()
full_path = StringVar()

Instead of those line:

entry.delete(0, END)
entry.insert(0, file_path+filename)

You can simply write:

full_path.set(file_path+filename)

Same with entry2 , instead of:

elif type == "path":
    full_path = askdirectory()
    entry2.delete(0, END)
    entry2.insert(0, full_path)

Write:

elif type == "path":
    full_path_dir = askdirectory()
    full_path.set(full_path_dir)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM