【问题标题】:Python strange NameError for def用于def的Python奇怪的NameError
【发布时间】:2020-06-18 11:05:38
【问题描述】:

我的代码不太长,所以这是整个程序,当我运行它时,它会说

NameError: name 'xmlp' is not defined for line 88

似乎太简单了,这里发生了什么? 它就在我提取并复制它并将其重命名为xmlp之前工作,然后我创建了一个新按钮来执行它但后来它坏了,为什么它说它没有定义,当它很清楚时?

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import tkinter as tk

import xml.etree.ElementTree as ET

interface = tk.Tk()
interface.geometry("900x500")
interface.title("Text display")

T = tk.Text(interface, height=20, width=150)
T.grid(column=1, row=2, columnspan=3)

def openfile(): # open your file and load it into the text widget

    global filename
    filename = filedialog.askopenfilename()
    print(filename)
    file = open(filename)
    global txt
    txt = file.read()

    T.delete('1.0', END)
    T.insert(tk.END, txt)

    return txt

def extract(): # take the opened file and write it to a text file
    open('somefile.txt', 'w').close()

    root = ET.fromstring(txt)

    str_params = root.findall('.//parameter/[parameterid="str"]')
    for param in str_params:
        if param.find('./name').text == 'Text':
            print(format(param.find('./value').text))
            with open('somefile.txt', 'a') as the_file:
                the_file.write(format(param.find('./value').text))
                the_file.write("\n")

    exportFileDir = open('somefile.txt',)

    txtExport = exportFileDir.read()

    T.delete('1.0', END)
    T.insert(tk.END,txtExport)

    def xmlp():  # take the opened file and write it to a text file
        open('somefile.txt', 'w').close()

        root = ET.fromstring(txt)

        str_params = root.findall('.//parameter/[parameterid="str"]')
        for param in str_params:
            if param.find('./name').text == 'Text2':
                print(format(param.find('./value').text))
                with open('somefile.txt', 'a') as the_file:
                    the_file.write(format(param.find('./value').text))
                    the_file.write("\n")

        exportFileDir = open('somefile.txt', )

        txtExport = exportFileDir.read()

        T.delete('1.0', END)
        T.insert(tk.END, txtExport)



def file_save():
    f = filedialog.asksaveasfile(mode='w', defaultextension=".txt")
    if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
        return
    exportFileDir = open('somefile.txt')

    txtExport = exportFileDir.read()

    f.write(txtExport)
    f.close() # `()` was missing.

button = ttk.Button(interface, text="Open text File", command=openfile)  # <------
button.grid(column=1, row=3, sticky = W)

buttonex = ttk.Button(interface, text="Extract subtitles", command=extract)  # <------
buttonex.grid(column=2, row=3, sticky = W)

buttonexp = ttk.Button(interface, text="X XML P", command=xmlp)  # <------
buttonexp.grid(column=2, row=4, sticky = W)

buttonsv = ttk.Button(interface, text="Save as", command=file_save)  # <------
buttonsv.grid(column=3, row=3, sticky = W)

interface.mainloop()

【问题讨论】:

  • 您的xmlp 函数在另一个函数中,因此它仅在该函数的范围内定义。

标签: python nameerror


【解决方案1】:

这里有缩进(间距和制表符)问题。 假设您复制了一个函数“function2”。你所做的是:

def function1():
    print('hello 1')

    def function2():
        print('hello 2')

def function3():
    print('hello 3')

但正确的做法是:

def function1():
    print('hello 1')

def function2():
    print('hello 2')

def function3():
    print('hello 3')

【讨论】:

  • 我明白了,非常感谢,我在 java 中被困了几个月,完全忘记了这一点
  • 另外,在从某处复制时,请记住,有时会复制空格而不是制表符 ('\t'),您可能会遇到“缩进错误”。因此,您将不得不删除空格并放置制表符。
【解决方案2】:

你在函数中定义了一个函数:

def hi():
    def hello():
        print("Hello")
    hello()
    print("Hi")
hello()  # <- Error

只存在于函数的本地范围内。

将函数移到函数之外,或者(如果你真的想使用这样的解决方案)使用global 在全局命名空间中定义它:

def hi():
    global hello
    def hello():
        print("Hello")
    hello()
    print("Hi")
hello()  # <- No error, after hi()

请注意,在这种情况下,需要首先调用定义内部函数(hello())的函数(hi())来执行global &lt;name&gt;,因此该函数被存储到@ 987654327@ 命名空间,而不是 local 一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多