为什么tkinter看不到定义的变量

2024-10-17 12:31:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在运行我的程序时,我遇到了一个问题。使用“save3”函数,我得到以下错误:

    Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:\Users\Medion\Desktop\PY - DOS GUI\OKNO.py", line 59, in save3
    d = pliktyped.get()
NameError: name 'pliktyped' is not defined

我在这里摘录了该函数:

def save():
    def save3():
        d = pliktyped.get()
        typed = str(d)
        plik = open(plek, 'w')
        plik.write(typed)
        menu()
    def save2():
        plek = str(pliksave.get())
        plik = open(plek, 'w')
        textsave2 = Label(okno, text="Text to be typed").grid(column=0, row=0)
        pliktyped = Entry(okno, width=10)
        pliktyped.grid(column=0, row=1)
        goSave2 = Button(okno, text="Type this text to file", command=save3).grid(column=1, row=1)
        
    for widget in okno.winfo_children():
        widget.destroy()
    foldery = Label(okno, text=folder, bg='lightblue').grid(column=0, row=3)
    folderyCo = Label(okno, text='Files:', bg='lightblue').grid(column=0, row=2)
    textsave = Label(okno, text="File to edit:").grid(column=0, row=0)
    pliksave = Entry(okno, width=10)
    pliksave.grid(column=0, row=1)
    goSave = Button(okno, text="Edit this file", command=save2).grid(column=1, row=1)

这可能是新手程序员的一个基本错误,但请提前感谢您的帮助


Tags: textingetdefcolumnlabelgridfile
2条回答

这是因为pliktypedsave2()内的局部变量,无法在save3()内访问它

实际上,您可以在save2()save3()内重用textsavepliksavegoSave而不是在save2()内创建新的小部件,因为它们放在初始创建的小部件的相同单元格中:

def save():
    def save3(plek):
        with open(plek, "w") as plik:
            plik.write(pliksave.get())
        menu()

    def save2():
        plek = pliksave.get()
        textsave.config(text="Text to be typed")
        goSave.config(text="Type this text to file", command=lambda:save3(plek))
        
    for widget in okno.winfo_children():
        widget.destroy()

    Label(okno, text=folder, bg='lightblue').grid(column=0, row=3)
    Label(okno, text='Files:', bg='lightblue').grid(column=0, row=2)

    textsave = Label(okno, text="File to edit:")
    textsave.grid(column=0, row=0)

    pliksave = Entry(okno, width=10)
    pliksave.grid(column=0, row=1)

    goSave = Button(okno, text="Edit this file", command=save2)
    goSave.grid(column=1, row=1)

因为名称空间不同。您在save2中设置它,而在save3中尝试访问它

使用Save2中的^ {CD1>}或考虑使用^ {CD2>}/P>

相关问题 更多 >