You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python的Tkinter askopenfilename调用Ubuntu原生文件对话框

让tkinter调用Ubuntu原生文件对话框的方案

在Ubuntu 22.04中,默认的tkinter.filedialog.askopenfilename()使用的是Tk自带的旧式对话框,无法直接调用Ubuntu原生的GTK风格对话框。你可以通过以下两种方案实现需求:

方案一:使用tkinter.tix组件

  1. 先安装依赖包:
sudo apt install python3-tix
  1. 修改后的示例脚本:
from tkinter import Tk
import tkinter.tix as tix

# 初始化主窗口并隐藏
root = Tk()
root.withdraw()

# 创建并弹出原生风格的文件选择对话框
file_dialog = tix.FileSelectDialog(root, title='Open file', filetypes=['*.bmp', '*'])
file_dialog.popup()

# 获取选中的文件路径
file_name = file_dialog.get_selection()
print(file_name)

方案二:使用PyGObject调用GTK原生对话框(推荐)

这个方案完全贴合Ubuntu系统的原生样式,功能更丰富:

  1. 安装依赖包:
sudo apt install python3-gi python3-gi-cairo gir1.2-gtk-3.0
  1. 示例脚本:
from gi.repository import Gtk

# 创建GTK文件选择对话框
dialog = Gtk.FileChooserDialog(
    title="Open file",
    parent=None,
    action=Gtk.FileChooserAction.OPEN,
    buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)
)

# 添加文件类型过滤
filter_bmp = Gtk.FileFilter()
filter_bmp.set_name("BMP files")
filter_bmp.add_pattern("*.bmp")
dialog.add_filter(filter_bmp)

filter_all = Gtk.FileFilter()
filter_all.set_name("All files")
filter_all.add_pattern("*")
dialog.add_filter(filter_all)

# 运行对话框并处理结果
response = dialog.run()
if response == Gtk.ResponseType.OK:
    print("选中的文件:", dialog.get_filename())
dialog.destroy()

内容的提问来源于stack exchange,提问作者Paul Jurczak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 08:41:08