AttributeError: у объекта 'str' нет атрибута 'tk' - PullRequest
0 голосов
/ 25 мая 2019

Я пытаюсь использовать 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 голосов
/ 26 мая 2019

Обратите внимание, что вы определяете значение для переменной scan4yellow тогда и только тогда, когда содержит желтый текст в docx.Когда я назначил переменную в вашем фрагменте вне внешнего цикла 'for' в функции scan_for_text, печатает значение очень хорошо.

Попробуйте отладить ваш код, используя

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...