importError: Cannot import name 'quitprogram' from 'GUIhelperFunction'

importError: Cannot import name 'quitprogram' from 'GUIhelperFunction'

我在同一文件夹中制作了 2 个 py 文件 'Main' 和 GUIHelperFunctions,我想在我的 main 文件中使用该模块中的函数 quitprogram,就像我刚刚在 main 文件本身中创建函数一样。但我收到

1importError: Cannot import name 'quitprogram' from GUIhelperFunction1.

我该如何解决?

我的代码在GUIHelperFunctions.py:

    def quitProgram():
        root.quit()

在我的 main.py:

    import numpy as np
    import beam as bm
    import matplotlib.pyplot as plt

    from GUIHelperFunctions import quitProgram
    import tkinter as tk  # tkinter is a GUI implementation Library

    HEIGHT = 480
    WIDTH = 640

    root = tk.TK()

    canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
    canvas.pack()

    # Creates a frame where GUI elements are drawn
    frame = tk.Frame(root)
    frame.place(relwidth=1, relheight=0.95)

    # Creating variables that are put into the frame GUI (start up)
    myLabel = tk.Label(frame, text="Deflection of beam Calculator", bg='yellow')


    quit = tk.Button(root, text="quit", bg='#AFAFAF', command=quitProgram)

    myLabel.pack()
    quit.pack()

    root.mainloop()

编辑 1:

我试图解决它更多,我 return 到这个 error 甚至我确保它是按照我的 post 写的。如果我将 GUIHelperFunction 中的函数放入我的 main 文件中,程序会冻结。

    Exception in Tkinter callback
    Traceback (most recent call last):
      File "C:\Users\chris\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
        return self.func(*args)
      File "C:\Users\chris\OneDrive\Desktop\code Assignments\Exam Project\GUIHelperFunctions.py", line 8, in quitProgram
    NameError: name 'root' is not defined

编辑 2:

好的,冻结是由于使用 root.quit() 而不是 root.destroy()。上面的问题仍然存在。

根据例外情况,您的问题不在于 quitProgram 函数的 import,而是函数本身。

NameError: name 'root' is not defined

当您 import 来自不同文件的函数时,它不知道所有主文件变量,即(在您的代码上下文中)root 变量未在 GUIHelperFunctions 因此它在 quitProgram 函数中无法识别因此它不能在那里使用 -> 结果出现 NameError 异常。

我建议进行以下更改以使其起作用:

  1. 更改 quitProgram 函数的签名:
def quitProgram(root):
    root.destroy()
  1. 使用相关参数调用函数:
quit = tk.Button(root, text="quit", bg='#AFAFAF', command=lambda: quitProgram(root))

请参阅 How to pass arguments to a Button command in Tkinter? 了解更多信息和示例。