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

Python中如何在类之间传递变量?(Tkinter场景)

Tkinter跨类传递变量解决方案

先修正原代码中的基础语法错误:

  • articles.py中__init__方法定义缺少冒号,应改为:
def __init__(self, master):
  • get_article_id方法未接收绑定事件传递的event参数,需修改为:
def get_article_id(self, event):

完整修改方案

1. 更新articles.py的事件处理逻辑

在获取到Treeview的选中项后,直接将变量传递给ArticleInfo实例:

# articles.py
from tkinter import ttk
from article_info import ArticleInfo

class Articles:
    def __init__(self, master):
        self.master = master
        # 初始化Treeview(示例)
        self.myTree = ttk.Treeview(master, columns=("ID", "标题"), show="headings")
        self.myTree.heading("ID", text="文章ID")
        self.myTree.heading("标题", text="文章标题")
        self.myTree.pack(padx=10, pady=10)
        # 绑定双击事件
        self.myTree.bind('Double-1', self.get_article_id)

    def get_article_id(self, event):
        # 获取双击的item对象
        item = self.myTree.identify("item", event.x, event.y)
        # 提取item的具体数据(比如文章ID)
        article_id = self.myTree.item(item)['values'][0]
        # 传递变量并创建弹窗
        ArticleInfo(self.master, article_id)

2. 修改article_info.py接收传递的变量

让ArticleInfo的构造方法接收父窗口和要显示的变量:

# article_info.py
from tkinter import Toplevel, Label

class ArticleInfo:
    def __init__(self, parent, article_id):
        # 以主窗口为父创建弹窗,关联窗口层级
        self.top = Toplevel(parent)
        self.top.title("文章详情")
        # 显示传递过来的变量
        Label(self.top, text=f"选中的文章ID:{article_id}").pack(padx=20, pady=20)

补充说明

  • 如果需要传递多行数据,可直接传递self.myTree.item(item)['values']元组,在ArticleInfo中拆分显示
  • 建议将类的导入语句放在文件顶部,避免事件触发时重复导入模块

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:43:12