NameError:name' root'在python 3中没有定义

时间:2018-01-30 10:27:15

标签: python-3.x nameerror

以下是我试图运行的程序

from tkinter import *
import tkinter as tk
from tkinter.ttk import *
from tkinter import LabelFrame, Label, Tk#, Canvas
from tkinter.ttk import Notebook
import tkinter.messagebox
import time
import os


import warnings
warnings.filterwarnings('ignore')

class GUIDesign():
    def __init__(self,root):
        self.initUI(root) 

    def initUI(self,root):
        print ("hello")

    LabelFrameFG="purple"
    LabelFrameBG="SNOW"

    note = Notebook(root)
    tab1 = Frame(note)
    tab6 = Frame(note)

def main():
    root = Tk()
    root.resizable(0,0)
    root.state('zoomed')
    GUI=GUIDesign(root)
    root.mainloop()

if __name__ == '__main__':
    main()

它给出错误:

Traceback (most recent call last):
File "E:\Python\tk.py", line 16, in <module>
class GUIDesign():
File "E:\Python\tk.py", line 35, in GUIDesign
note = Notebook(root)
NameError: name 'root' is not defined

问题在于导入Notebook?还是班级及其功能?还是python的版本问题?有谁能告诉我这个程序有什么问题吗?

1 个答案:

答案 0 :(得分:0)

您应该将root定义为全局变量。你的代码应该是这样的。

from tkinter import *
import tkinter as tk
from tkinter.ttk import *
from tkinter import LabelFrame, Label, Tk#, Canvas
from tkinter.ttk import Notebook
import tkinter.messagebox
import time
import os


import warnings
warnings.filterwarnings('ignore')

root = Tk()

class GUIDesign():
    def __init__(self,root):
        self.initUI(root) 

    def initUI(self,root):
        print ("hello")

    LabelFrameFG="purple"
    LabelFrameBG="SNOW"

    note = Notebook(root)
    tab1 = Frame(note)
    tab6 = Frame(note)


def main():
    root = Tk()
    root.resizable(0,0)
    root.state('zoomed')
    GUI=GUIDesign(root)
    root.mainloop()

if __name__ == '__main__':
    main()