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

如何将主文件的clicked函数导入外部文件类?解决NameError问题

问题解决方法

要解决NameError: name 'clicked' is not defined的问题,只需将主文件中的clicked函数作为参数传递给Page1类的实例,并在Page1内部使用该参数即可,具体步骤如下:

1. 修改主文件,传递clicked函数到Page1实例

在主文件中创建Page1对象时,将clicked作为参数传入,同时修正按钮command参数的错误写法:

import tkinter as tk
from tkinter import ttk
from page1 import *

root = tk.Tk()
root.geometry('480x320')

style = ttk.Style()
style.theme_use('default')
style.configure('TNotebook', tabposition='ws', background='white', tabmargins=0)

nb = ttk.Notebook(root)
nb.pack(fill='both', expand=1)

datalist = []
        
def clicked(flag, func):
    if flag:
        datalist.append(func())
    else:
        datalist.remove(func())

def try_print():
    if len(datalist) > 0:
        print("ok")

# 实例化Page1时传入clicked函数
page1 = Page1(nb, clicked=clicked)
nb.add(page1, text='Page 1', compound='left')

# 修正command参数:去掉括号,否则程序启动时会直接执行try_print
button = tk.Button(root, text="Print", command=try_print)
button.place(x=60, y=100)

root.mainloop()

2. 修改Page1类,接收并使用clicked参数

修改Page1的__init__方法,新增clicked参数,并在复选框的lambda中调用该传入的函数:

import tkinter as tk
from tkinter import ttk

class Page1(tk.Frame):
    def __init__(self, master, clicked, **kw):
        super().__init__(master, **kw)

        Checkbutton1 = tk.IntVar()

        def Button1_func():
            x = "test"
            return x
  
        Button1 = tk.Checkbutton(self, text = "Checkbox1", variable = Checkbutton1, onvalue = 1, offvalue = 0, height = 1,
                                 bg="white", foreground='black', activebackground="white", highlightthickness = 0,
                                 # 调用传入的clicked函数
                                 command=lambda: clicked(Checkbutton1.get(), Button1_func))
        Button1.place(x=10, y=30)

关键说明

  • 通过将clicked函数作为参数传递给Page1,既实现了主文件函数在子模块中的调用,又保持了代码结构的分离。
  • 主文件中Button的command=try_print()会导致程序启动时立即执行try_print,点击按钮时反而无响应,因此要改为command=try_print。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:35:35