如何使用Tkinter Treeview控件实现双击或点击按钮打开对应PDF文件
实现方案
核心逻辑说明
- 插入Treeview节点时,将叶子节点对应的PDF完整本地路径存储到节点的
values属性中,非叶子节点可留空 - 两种触发方式均通过获取选中节点的存储路径,调用Bluebeam程序打开对应文件
1. 双击叶子节点打开PDF实现
首先给Treeview绑定双击事件,回调函数中先判断是否为叶子节点、是否存在关联PDF路径,校验通过后执行打开逻辑:
import tkinter as tk from tkinter import ttk import subprocess import os # 替换为你本地Bluebeam的实际安装路径 BLUEBEAM_PATH = r"C:\Program Files\Bluebeam Software\Bluebeam Revu\20\Revu\Revu.exe" # 替换为你的PDF根目录路径 PDF_ROOT = r"C:\Users\你的用户名\Desktop\你的PDF总目录" def on_double_click(event): # 获取点击的节点iid item = tree.identify('item', event.x, event.y) if not item: return # 判断是否为叶子节点(无children就是叶子节点) if not tree.get_children(item): # 取节点存储的PDF路径 pdf_path = tree.item(item, 'values')[0] if tree.item(item, 'values') else '' if pdf_path and os.path.exists(pdf_path): # 调用Bluebeam打开 subprocess.Popen([BLUEBEAM_PATH, pdf_path]) # 你的原有Treeview代码修改,插入节点时加values存路径 tree = ttk.Treeview(vender_class) tree.pack(fill=tk.BOTH, expand=True) # 根节点不需要存路径 tree.insert(parent='', index='end', iid=1, text="Thresholds") tree.insert(parent='1', index='end', iid=2, text="Butt Hung") # 叶子节点存对应PDF完整路径 tree.insert(parent='2', index='end', iid=3, text="THBH", values=(os.path.join(PDF_ROOT, r"Thresholds\Butt Hung\THBH.pdf"),)) tree.insert(parent='1', index='end', iid=4, text="Center Hung") tree.insert(parent='4', index='end', iid=5, text="THCH", values=(os.path.join(PDF_ROOT, r"Thresholds\Center Hung\THCH.pdf"),)) tree.insert(parent='1', index='end', iid=6, text="Offset Hung") tree.insert(parent='6', index='end', iid=7, text="THOH", values=(os.path.join(PDF_ROOT, r"Thresholds\Offset Hung\THOH.pdf"),)) tree.insert(parent='1', index='end', iid=8, text="Other") tree.insert(parent='8', index='end', iid=9, text="THO", values=(os.path.join(PDF_ROOT, r"Thresholds\Other\THO.pdf"),)) # 绑定双击事件 tree.bind("<Double-1>", on_double_click)
2. 选中节点后点击按钮打开实现
如果需要按钮触发,新增按钮的回调函数即可,逻辑和双击逻辑一致:
def openfile(): # 获取选中的节点 selected_items = tree.selection() if not selected_items: return item = selected_items[0] # 仅叶子节点可打开 if not tree.get_children(item): pdf_path = tree.item(item, 'values')[0] if tree.item(item, 'values') else '' if pdf_path and os.path.exists(pdf_path): subprocess.Popen([BLUEBEAM_PATH, pdf_path]) open_button=ttk.Button(vender_class, text="Open PDF", command=openfile) open_button.pack(pady=5)
注意事项
- 替换代码中的
BLUEBEAM_PATH为你本地Bluebeam的实际安装路径,不同版本的Revu路径会有差异 - 如果你不需要强制用Bluebeam打开,也可以用
os.startfile(pdf_path)直接调用系统默认PDF阅读器打开,更简单 - 如果你需要自动遍历目录生成Treeview,只需要写递归遍历逻辑,遍历文件夹的时候动态插入节点,同时拼接PDF路径存到对应叶子节点的values里即可,不需要手动写每个insert代码
内容的提问来源于stack exchange,提问作者Austin Sims
相关产品推荐
相关产品推荐

