[英]importError: Cannot import name 'quitprogram' from 'GUIhelperFunction'
我在同一个文件夹中GUIHelperFunctions
了 2 个 py 文件 'Main' 和GUIHelperFunctions
,我想在我的main
文件中使用该模块中的函数quitprogram
,就像我刚刚在main
文件中创建函数一样。 但我得到了
1importError:无法从 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:
我试图再解决一些问题,即使那样我也会回到这个error
我确保它是按照我的帖子写的。 如果我将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:未定义名称“root”
当您从不同的文件中import
函数时,它不知道所有主文件变量,即(在您的代码上下文中) root
变量未在GUIHelperFunctions
定义,因此在quitProgram
函数中无法识别,因此它可以' t 在那里使用 -> 带有NameError
异常的结果。
我建议进行以下更改,以便它起作用:
quitProgram
函数的签名:def quitProgram(root):
root.destroy()
quit = tk.Button(root, text="quit", bg='#AFAFAF', command=lambda: quitProgram(root))
请参阅如何将参数传递给 Tkinter 中的按钮命令? 有关更多信息和示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.