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

Python3.11.4:如何从book1的CRUD类导入方法到主文件Book类中调用?

解决Tkinter按钮调用外部类方法的问题

问题场景

主文件的Book类中,create_books方法需要将book1文件里CRUD类的create_books_fun方法设置为按钮的command回调函数。已通过from book1 import *导入内容,但无法正常调用。

主文件代码

from book1 import *
import tkinter as tk
from tkinter.messagebox import showinfo, showerror

class Book:
    def __init__(self):
        self.win = tk.Tk()
        self.win.title('Записная книга')
        self.win.geometry("503x150")
 
        self.build_main_window()
        self.win.mainloop()

    def build_main_window(self):
        self.create_title()
        self.create_books()
        self.read_books()
        self.delete_books()
        self.add_books()

    def create_title(self):
        title = tk.Label(self.win, text='Записная книга', font='Arial 16 bold')
        title.grid(row=0, column=0, columnspan=4, padx=20, pady=20, sticky='ew')
 
    def create_books(self):
        self.create_but = tk.Button(self.win, text='Добавить запись', command=self.create_books_fun)#this should be called from book1, def create_books_fun
        self.create_but.grid(row=1, column=0, columnspan=1, padx=10, pady=10)

book1文件代码

class CRUD:
    def create_books_fun():
        pass

错误原因

  1. 方法路径错误:主文件中command=self.create_books_fun是在Book类实例中查找方法,而目标方法属于CRUD类,路径不匹配。
  2. 类方法定义不规范:CRUD类的create_books_fun既没有self参数(实例方法要求),也没有声明为静态/类方法,调用时会触发参数不匹配错误。

解决方案

根据create_books_fun的功能需求,选择以下任一方案:

方案1:将方法改为实例方法

适用于需要访问CRUD类实例属性的场景。

  • 修改book1中的代码,为方法添加self参数:
    class CRUD:
        def create_books_fun(self):
            # 写入具体业务逻辑,比如弹出输入窗口、操作数据库等
            print("执行添加记录操作")
    
  • 修改主文件create_books方法,实例化CRUD后调用其方法:
    def create_books(self):
        # 实例化CRUD类
        crud_instance = CRUD()
        self.create_but = tk.Button(self.win, text='Добавить запись', command=crud_instance.create_books_fun)
        self.create_but.grid(row=1, column=0, columnspan=1, padx=10, pady=10)
    
    如果需要在多个方法中复用CRUD实例,可在Book类的__init__中初始化:
    def __init__(self):
        self.win = tk.Tk()
        self.win.title('Записная книга')
        self.win.geometry("503x150")
        # 初始化CRUD实例
        self.crud = CRUD()
        self.build_main_window()
        self.win.mainloop()
    
    def create_books(self):
        self.create_but = tk.Button(self.win, text='Добавить запись', command=self.crud.create_books_fun)
        self.create_but.grid(row=1, column=0, columnspan=1, padx=10, pady=10)
    

方案2:将方法设为静态方法

适用于不需要访问CRUD类或实例属性的场景。

  • 修改book1中的代码,添加@staticmethod装饰器:
    class CRUD:
        @staticmethod
        def create_books_fun():
            # 写入具体业务逻辑
            print("执行添加记录操作")
    
  • 修改主文件create_books方法,直接通过类名调用静态方法:
    def create_books(self):
        self.create_but = tk.Button(self.win, text='Добавить запись', command=CRUD.create_books_fun)
        self.create_but.grid(row=1, column=0, columnspan=1, padx=10, pady=10)
    

方案3:将方法设为类方法

适用于需要访问CRUD类属性的场景。

  • 修改book1中的代码,添加@classmethod装饰器并传入cls参数:
    class CRUD:
        # 示例类属性
        some_class_attr = "test"
    
        @classmethod
        def create_books_fun(cls):
            # 可通过cls访问类属性
            print(f"类属性值:{cls.some_class_attr}")
            print("执行添加记录操作")
    
  • 主文件的调用方式与静态方法一致:
    def create_books(self):
        self.create_but = tk.Button(self.win, text='Добавить запись', command=CRUD.create_books_fun)
        self.create_but.grid(row=1, column=0, columnspan=1, padx=10, pady=10)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 01:58:11