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

使用Tkinter上传MS Access文件并读取展示数据的问题求解

需求说明
  • 支持选择并读取.mdb/.accdb格式的MS Access文件
  • 按预设SQL语句查询文件内数据
  • 将查询结果渲染到GUI中已预留的frame控件内
  • 基于已有的Tkinter基础GUI代码补全逻辑,无需重构原有界面
前置准备

执行以下命令安装数据库读取依赖:

pip install pyodbc

注意:需提前在本地安装与Python架构(32/64位)一致的Microsoft Access ODBC驱动,否则无法正常建立数据库连接。

完整实现代码
import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import pyodbc

# 替换为你自己的预设查询语句
PRESET_SQL = "SELECT * FROM 你的目标表名"

root = tk.Tk()

def addFile():
    filename = filedialog.askopenfilename(
        initialdir="/",
        title="Select File",
        filetypes=(("Microsoft Access", "*.mdb *.accdb"), ("all files", "*.*"))
    )
    if not filename:
        return
    
    # 清空frame内原有内容
    for widget in frame.winfo_children():
        widget.destroy()
    
    try:
        # 建立Access数据库连接
        conn_str = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + filename
        conn = pyodbc.connect(conn_str)
        cursor = conn.cursor()
        cursor.execute(PRESET_SQL)
        
        # 获取查询结果列名与数据
        columns = [col_desc[0] for col_desc in cursor.description]
        rows = cursor.fetchall()
        
        # 在frame中渲染表格
        scroll_y = ttk.Scrollbar(frame, orient=tk.VERTICAL)
        scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
        
        tree = ttk.Treeview(
            frame,
            columns=columns,
            show="headings",
            yscrollcommand=scroll_y.set
        )
        scroll_y.config(command=tree.yview)
        
        # 配置列头
        for col in columns:
            tree.heading(col, text=col)
            tree.column(col, width=100, anchor=tk.CENTER)
        
        # 插入数据行
        for row in rows:
            tree.insert("", tk.END, values=list(row))
        
        tree.pack(fill=tk.BOTH, expand=True)
        
        # 关闭连接
        cursor.close()
        conn.close()
    
    except Exception as e:
        messagebox.showerror("读取错误", f"文件读取失败:{str(e)}")

canvas = tk.Canvas(root, height=500, width=500, bg="#263d42")
canvas.pack()

openFile = tk.Button(root, text="Open File", padx=10, pady=5, fg="#263d42", bg="white", command=addFile)
openFile.pack()

frame = tk.Frame(root, bg="white")
frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1)

root.mainloop()
自定义修改说明
  • 将代码开头的PRESET_SQL变量值替换为你实际需要执行的查询语句,确保语句中的表名、字段名和选中的Access文件结构匹配
  • 如果需要调整列宽,修改tree.column(col, width=100)中的width参数即可
  • 若需要处理超大量数据,可以给查询加分页逻辑,避免一次性加载所有数据导致界面卡顿

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 11:48:27