导入错误: 无法从"GUIhelperFunction"导入名称"退出程序"



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

1importError: 無法從 GUIhelperFunction1 中進取名稱 'quitprogram'。

我该如何解决?

我在 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:

我试图再解决一些问题,然后我回到这个error即使这样,我也会确保它是按照我的帖子编写的。如果我将GUIHelperFunction中的函数放入我的main文件中,程序将冻结。

Exception in Tkinter callback
Traceback (most recent call last):
File "C:UserschrisAppDataLocalProgramsPythonPython37-32libtkinter__init__.py", line 1705, in __call__
return self.func(*args)
File "C:UserschrisOneDriveDesktopcode AssignmentsExam ProjectGUIHelperFunctions.py", line 8, in quitProgram
NameError: name 'root' is not defined

编辑 2:

好的,冻结是由于使用root.quit()而不是root.destroy()。不过,上述问题仍然是实际的。

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

名称

错误:未定义名称"根">

当您从不同的文件中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))

请参阅如何将参数传递给 Tkinter 中的按钮命令?以获取更多信息和示例。

最新更新