非常抱歉给你带来困惑。以下是重新排版后的代码示例:
import tkinter as tk
from tkinter import ttk
def show_cell_content(event):
selected_item = tree.identify_row(event.y) # 获取鼠标所在的行
column = tree.identify_column(event.x) # 获取鼠标所在的列
if selected_item and column: # 确保有选中行和列
cell_value = tree.item(selected_item)[int(column) - 1] # 获取单元格的值
if hasattr(root, 'top'):
root.top.destroy()
top = tk.Toplevel(root)
root.top = top # 将top作为root的属性保存
top.title('Cell Content')
label = tk.Label(top, text=cell_value)
label.pack()
x = root.winfo_x() + event.x + 10 # 窗口相对于root的x坐标,加10是为了避免重叠
y = root.winfo_y() + event.y + 10 # 窗口相对于root的y坐标,加10是为了避免重叠
top.geometry(f'+{x}+{y}')
def hide_cell_content(event):
if hasattr(root, 'top'):
root.top.destroy()
root = tk.Tk()
tree = ttk.Treeview(root, columns=('Column1', 'Column2'))
tree.heading('#0', text='Item')
tree.heading('Column1', text='Value 1')
tree.heading('Column2', text='Value 2')
tree.insert("", "end", text="Item 1", values=("Value 1.1", "Value 1.2"))
tree.insert("", "end", text="Item 2", values=("Value 2.1", "Value 2.2"))
tree.insert("", "end", text="Item 3", values=("Value 3.1", "Value 3.2"))
tree.bind('<Motion>', show_cell_content) # 鼠标移动到单元格上时显示内容窗口
tree.bind('<Leave>', hide_cell_content) # 移出单元格时隐藏内容窗口
tree.pack()
root.mainloop()
希望这个重新排版后的代码能够更好地满足你的需求!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |