Ubuntu下Python3.6调用filedialog.askdirectory显示旧版对话框求助
Ah, I get it—this is a common issue with Tkinter on Ubuntu! The default filedialog from Tkinter uses the old GTK2-style dialog, which looks totally out of place next to Ubuntu's modern GTK3 desktop. Let me show you two solid ways to get that native, up-to-date file picker instead:
This is the most robust approach since it directly uses the same GTK3 libraries that Ubuntu's desktop environment relies on. Here's how to set it up:
- First, install the required dependencies via apt:
sudo apt-get install python3-gi python3-gi-cairo gir1.2-gtk-3.0
- Then use this code to create a native directory picker:
from gi.repository import Gtk def pick_directory(): # Create the directory selection dialog dialog = Gtk.FileChooserDialog( title="Choose a Directory", action=Gtk.FileChooserAction.SELECT_FOLDER, buttons=( Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK ) ) # Set a reasonable default window size dialog.set_default_size(800, 600) # Run the dialog and get user response response = dialog.run() selected_dir = None if response == Gtk.ResponseType.OK: selected_dir = dialog.get_filename() print(f"Selected directory: {selected_dir}") # Clean up the dialog dialog.destroy() return selected_dir if __name__ == "__main__": pick_directory()
This will pop up Ubuntu's native file dialog—complete with sidebar shortcuts, dark mode support, and all the modern UI elements you expect.
If you don't want to mess with GUI libraries, Zenity is a great alternative. It's a command-line tool that spawns native GTK dialogs, and it's pre-installed on most Ubuntu GNOME setups.
Here's the code to call it from Python:
import subprocess def pick_directory_with_zenity(): try: # Run Zenity's directory selection command result = subprocess.run( ["zenity", "--file-selection", "--directory", "--title=Select a Directory"], capture_output=True, text=True ) if result.returncode == 0: # Strip the trailing newline from the output selected_dir = result.stdout.strip() print(f"Selected directory: {selected_dir}") return selected_dir else: print("User canceled the selection.") return None except FileNotFoundError: print("Zenity isn't installed! Install it with: sudo apt-get install zenity") return None if __name__ == "__main__": pick_directory_with_zenity()
This is a lightweight option that gets the job done without needing to import heavy GUI frameworks.
内容的提问来源于stack exchange,提问作者RobbieZhao




