AttributeError:“ str”对象没有属性“ tk”

时间:2019-05-25 20:28:28

标签: python tkinter

我正在尝试在另一个函数scan4yellow中使用def scan_for_text():中的def home_screen():,然后使用scan4yellow中的结果并将它们打印在标签上,但一直在说即使在home_screen()中将其定义为全局变量,也不会在scan_for_text():函数中定义它

    global scan4yellow
    ##reads in the specific docx you want
    document = docx.Document(r'C:/Users/devff/Documents/Prac2.docx')
    ##makes it so it is an element that is actually editable and usable
    rs = document._element.xpath("//w:r")
    ##microsoft words schema so it knows what the xml is like and the parametres
    WPML_URI = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
    ##bits and pieces to help find the highlighted pieces of text
    ##then leads onto if statements finding out the highlighted texts colour
    tag_rPr = WPML_URI + 'rPr'
    tag_highlight = WPML_URI + 'highlight'
    tag_val = WPML_URI + 'val'
    tag_t = WPML_URI + 't'
    for word in rs:
        for rPr in word.findall(tag_rPr):
            high = rPr.findall(tag_highlight)
            for hi in high:
                if hi.attrib[tag_val] == 'yellow':
                    scan4yellow = (word.find(tag_t).text.encode('utf-8').lower())
                    #return scan4yellow
                    print(scan4yellow)


def home_screen():
    global home_screen
    global scan4yellow
    home_screen = Toplevel(login_screen)
    home_screen.title("Home Page")
    home_screen.geometry("800x600")

    b1 = Button(home_screen, text="Select File", bg="white", command=getfile)
    l1 = Label(home_screen, bg="white", width="20")
    b2 = Button(home_screen, text="Scan File", width=8, bg="white", command=scan_for_text)
    b3 = Button(home_screen, text="Logout", width=8, bg="white", command=logout)
    b4 = Button(home_screen, text="Quit", width=8, bg="white", command=quit)
#    l1 = Label(home_page, textvariable=scan4yellow).grid(row=3, column=1, padx=(10, 0), pady=(10, 0))
#    t1 = Text.insert(END, "1.0", scan4yellow).grid(row=3, column=1, padx=(10, 0), pady=(10, 0))
    l2 = Label(home_screen, text=scan4yellow) #<----- problem is here 'scan4yellow' is not defined
    #print(scan4yellow)```

1 个答案:

答案 0 :(得分:0)

请注意,如果且仅当 docx中有黄色文本时,才将scan4yellow变量的值定义为。当我在scan_for_text函数中最外面的“ for”循环外的代码段中分配了变量时,就可以正常打印值。

尝试使用调试代码

import pdb; pdb.set_trace()

恰好在scan4yellow分配之前,然后向上移动直到命中为止。我很确定您错过了一些docx标签(或您的输入文件中没有黄色文字)。

或者根本不调用scan_for_text。在这种情况下,全局变量保持未定义状态。

#! /usr/bin/env python3

def scan_for_text():
    global scan4yellow
    if True: # change to False to see your error again
        scan4yellow = 'Whatever'

def home_screen():
    # global scan4yellow # you don't even need it declared global again

    print(scan4yellow)

scan_for_text()
home_screen() #prints "Whatever" as long as scan_for_text is called BEFORE home_screen function