【问题标题】:Reloading the specified function from separate files从单独的文件重新加载指定的函数
【发布时间】:2020-12-04 19:45:27
【问题描述】:

在文件 a 中有一个按钮,它从文件 b 中调用函数的执行,然后将其删除。然后创建另一个按钮,该按钮应将 gui 重置为其原始状态。

不幸的是,我不知道如何正确配置它以使其工作。 在尝试修复它时,您最终遇到了以下错误:

ImportError:无法从部分初始化的模块“b”导入名称“GUI”(很可能是由于循环导入)(c:\Users\user\Desktop\english_app\b.py) TypeError: back() 缺少 1 个必需的位置参数:'root'

文件:

from tkinter import *
from b import dest
from functools import partial
class Gui:
    def __init__(self, root):
        self.b = Button(root, text='destroy', command=partial(dest, root))
        self.b.pack()

if __name__ == "__main__":
    root = Tk()
    Gui(root)
    mainloop()

文件 b:

from tkinter import *
class dest:
    def __init__(self, root):
        for widget in root.winfo_children():
            widget.destroy()

        self.b_back = Button(root, text="Back", command=self.back)
        self.b_back.pack()

    def back(self, root):
        for widget in root.winfo_children():
            widget.destroy()
       
        Gui(root)

【问题讨论】:

  • 在文件 b 中,它应该来自导入 GUI 吗?
  • 你在哪里实例化 dest 类?
  • 它解决了你的错误吗?
  • 当我尝试这样做时,我尝试了所有可行的方法并忘记将其删除。没用
  • 如果 a 从 b 导入,b 如何使用 Gui(在 a 中定义)?这会导致循环依赖

标签: python python-3.x tkinter


【解决方案1】:

需要使用不带fromimport 语句以避免循环导入。 例如:

文件 a.py:

from tkinter import *
import b
from functools import partial
class Gui:
    def __init__(self, root):
        self.b = Button(root, text='destroy', command=partial(b.dest, root))
        self.b.pack()

if __name__ == "__main__":
    root = Tk()
    Gui(root)
    mainloop()

文件 b.py:

from tkinter import *
import a

class dest:
    def __init__(self, root):
        for widget in root.winfo_children():
            widget.destroy()

        self.b_back = Button(root, text="Back", command=self.back(root))
        self.b_back.pack()

    def back(self, root):
        for widget in root.winfo_children():
            widget.destroy()
       
        a.Gui(root)

【讨论】:

  • 当我点击返回时,出现以下错误:TypeError: back() missing 1 required positional argument: 'root'
  • 哦,对了,我不明白在这种情况下你想要什么功能,但你可以通过在第 9 行将 root 参数提供给 self.back(root) 来修复类型错误。self.b_back = Button(root, text="Back", command=self.back(root))跨度>
猜你喜欢
  • 2013-11-04
  • 2020-03-08
  • 1970-01-01
  • 2016-07-04
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 1970-01-01
  • 2010-12-26
相关资源
最近更新 更多