Python中能否同时存储目录与文件路径?新手GUI开发问题求助
Hey there! I see the issue you're running into—you're trying to store both a directory path and a file path, but right now your code is overwriting the variables linking to your entry boxes, so only one path gets tracked properly. Let's fix that step by step.
What's Going Wrong?
The core problem is you're reusing the same root.entryVariable and root.entry names twice:
root.entryVariable = tkinter.StringVar() root.entry = tkinter.Entry(frame,textvariable=root.entryVariable) # ... later ... root.entryVariable = tkinter.StringVar() # This overwrites the first variable entirely! root.entry = tkinter.Entry(frame,textvariable=root.entryVariable) # Same for the entry box
When you click either button, it only updates the second entry box because the first variable and entry instance got replaced when you re-assigned those names.
The Fixed Code
Here's an adjusted version where each entry box has its own dedicated variable, and button callbacks target the correct field:
import tkinter import tkinter.filedialog def OnDirectoryButtonClick(target_var, target_entry): # Update the directory-specific variable and entry box target_var.set(tkinter.filedialog.askdirectory()) target_entry.focus_set() target_entry.selection_range(0, tkinter.END) def OnFileButtonClick(target_var, target_entry): # Update the file-specific variable and entry box target_var.set(tkinter.filedialog.askopenfilename()) target_entry.focus_set() target_entry.selection_range(0, tkinter.END) root = tkinter.Tk() frame = tkinter.Frame(root) # --- Directory path section --- dir_var = tkinter.StringVar() dir_entry = tkinter.Entry(frame, textvariable=dir_var) dir_entry.grid(column=0, row=1) dir_button = tkinter.Button(frame, text="Choose Directory", command=lambda: OnDirectoryButtonClick(dir_var, dir_entry)) dir_button.grid(column=1, row=1) # --- File path section --- file_var = tkinter.StringVar() file_entry = tkinter.Entry(frame, textvariable=file_var) file_entry.grid(column=0, row=3) file_button = tkinter.Button(frame, text="Choose File", command=lambda: OnFileButtonClick(file_var, file_entry)) file_button.grid(column=1, row=3) frame.pack(pady=9) root.mainloop()
Key Changes Explained:
- Created separate
StringVarinstances (dir_varandfile_var) for each entry box—no more overwriting variables. - Updated callback functions to accept the specific variable and entry box they need to modify, instead of relying on ambiguous
rootreferences. - Renamed buttons for clarity (optional, but makes the UI more intuitive).
- Linked each button directly to its corresponding variable and entry via the lambda function.
Now when you click "Choose Directory", it updates the first entry box, and "Choose File" updates the second. You can access the stored paths anytime using dir_var.get() and file_var.get().
内容的提问来源于stack exchange,提问作者Kevin Winnik

