Frage

    def check_answer(self, currentscore):
    self.user_entry = self.user_entry.get_text()
    if self.user_entry == self.books:
        self.current += 1
        self.total += 1
        self.currentscore = self.current
        print "right"
    else:
        print "wrong"
        print self.currentscore
        print self.total

When i run it and i put text a second time is says File "C:\Python27\guessing.py", line 16, in check_answer self.user_entry = self.user_entry.get_text() AttributeError: 'str' object has no attribute 'get_text' Could someone explain it to me. Why it to me why it only works once. and also why doesn't the program execute the if statement. It only says wrong.

self.books = 'hello'

War es hilfreich?

Lösung

You overwrite the variable holding the reference to the text box with its contents. So when check_answer runs for the first time, self.user_entry is your text box, and you can call its method get_text() to retrieve the text entered by the user. Unfortunately, you assign this text to the same variable (self.user_entry =) - so you loose the reference to the text box. After the first call, self.user_entry is a string (instance of str class) retrieved at the first call.

Use a different variable name, like this:

def check_answer(self, currentscore):
    self.user_entry_text = self.user_entry.get_text()
    if self.user_entry_text == self.books:
        self.current += 1
        self.total += 1
        self.currentscore = self.current
        print "right"
    else:
        print "wrong"
        print self.currentscore
        print self.total

Also, possibly it doesn't have to be class's field, so you can also skip the self. part. In such case you could use the same name (user_entry), but for sake of readability it's better to call a variable with a name that says precisely what the variable holds:

    user_entry_text = self.user_entry.get_text()
    if user_entry_text == self.books:
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top