etree findall不在函数内部工作

时间:2017-09-11 04:08:22

标签: python

我很困惑。 我之前写过这段小代码并在其他地方使用它:

def testBut(p):
    print(root)
    for items in root.findall("a/item"):
        print(items.get("name"))

它运作得很好。

但现在在我的新项目中,我有以下代码:

for items in root.findall("a/item"):
print(items.get("name"))

def testBut(p):
    print(root)
    for items in root.findall("a/item"):
        print(items.get("name"))

所以外面的def。它工作得很好,并向我展示了a中的所有项目,其中除了root之外我只得到root(因为我打印它)。任何人都可以解释原因吗?

我很抱歉,如果这是转贴或其他什么,但我根本找不到答案,特别是考虑到它在不同的文件中工作得很好,但设置完全相同..

编辑:完整(ish)代码。

from tkinter import *
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
import xml.etree.ElementTree as ET

tree = ET.parse("Alphabet.xml")
root = tree.getroot()

colour0 = "WHITE"
colour1 = "OLIVEDRAB1"
colour2 = "PALETURQUOISE1"
colour3 = "ROSYBROWN1"
font1 = "Arial, 24"
counterRow = 1
counterColumn = 0

for items in root.findall("a/item"):
    print(items.get("name"))

def testBut(p):
    print(root)
    for items in root.findall("a/item"):
        print("test")
        print(items.get("name"))

def setup():
    for letters in root:
        global counterRow
        global counterColumn

        letters.tag = Button(vindue, text=letters.tag, font=font1,
                             command=lambda p=letters.tag: testBut(p))\
            .grid(row=counterRow, column=counterColumn, sticky="nsew")
        counterColumn += 1
        if counterColumn > 7:
            counterRow += 1
            counterColumn = 0


def reset():
    for buttons in vindue.grid_slaves():
        if buttons.grid_info()["row"] > 0:
            buttons.grid_forget()


def showBut(input):
    counter = 0
    reset()
    lst = []
    print(input)
    str = input+"/item"
    print(str)
    for items in root.findall("a/item"):
        print(items.get("name"))
        print("test")
        varstr = items.get("name")+"Var"
        varstr = IntVar()
        varstr2 = items.get("name")
        varstr2 = Button(vindue, text=items.get("name"), font="Arial, 44", command=lambda varstr=varstr: (varstr.set(varstr.get() + 1), print(varstr.get())))
        varstr2.grid(row=1, column=counter)
        counter += 1




vindue = Tk()

setup()

vindue.mainloop()

0 个答案:

没有答案