Как использовать виджеты входа в Tkinter в цикле - PullRequest
0 голосов
/ 09 июля 2020

Я создаю игру Mad Libs, в которую много пользовательского ввода. Я создал функцию для получения всех входных данных в списке, учитывая список типов слов. Сообщение об ошибке отсутствует, но окно пустое. Я попытался распечатать список wordInputs, и он получил:

[ >,

и так далее. Я предполагаю, что это связано с тем, что он удалил все виджеты, но я подумал, что он сделает это только после того, как я их введу. Я тоже не совсем уверен, как сохранить ввод в переменной; мне создать кнопку для этого или что-то в этом роде? Вот код:

from tkinter import *

class Game:
    #Gets user input for a specified type of word
    def getWord(self, words):
        wordInputs = []
        for i in range(len(words)):
            frame = Frame(self.windowSnowDay)
            frame.pack()
            Label(frame, text = "\nSnow Day\n________\n").grid(row = 1, column = 1, columnspan = 2)
            Label(frame, text = "Enter a(n) " + words[i] + ":").grid(row = 2, column = 1)
            word = StringVar()
            Entry(frame, textvariable = word).grid(row = i + 2, column = 2)
            wordInputs.append(word.get)
            frame.destroy()
        return wordInputs

    #Executes "Snow Day" story from Mad Libs menu
    def snowDay(self):
        self.windowMadLibs.destroy()
        self.windowSnowDay = Tk()
        self.windowSnowDay.title("Snow Day")
        self.windowSnowDay.geometry("200x200")
        frame = Frame(self.windowSnowDay)
        frame.pack()
        #Collects words and stores them in a list
        words = ["verb", "electronic device", "public place", "adjective", "verb ending with -ing", "color", "noun", "noun", "drink", \
            "clothing item", "adjective", "3-dimensional shape", "adjective", "plural noun", "adjective", "feeling (adjective)", "food"]
        wordInputs = self.getWord(words)
        print(wordInputs)
        self.windowSnowDay.mainloop()
        #Prints "Snow Day" story with all inputted words
        print("\nAll the children cheer in", emotion, "as they", verb, "that morning. They hear on the", device,"that the", place, end =' ')
        print("is closed because of a snowstorm. They think of all the", adj, "things they could do today, such as", verb1, "on a", end = ' ')
        print(color, noun + ". Maybe they can even make a snow" + noun1 + "! They go inside, where a warm cup of", drink, "awaits", end = ' ')
        print("them. Before going outside, they put on their scarves and", clothing, "so that they don't get", adj1 + ". They", end = ' ')
        print("make a snow" + noun1, "out of 3 large", shape + "s, but it quickly fell apart because the snow wasn't very", adj2, end = '. ')
        print("After that, one of the", noun2, "attacked another, and it turned into a", adj3, "snowball fight. They were so", feeling, end = ' that ')
        print("they went straight to bed. Oh well, I guess they can eat the leftovers of Mom's famous", food, "tomorrow!")

    #Main function for Mad Libs
    def madLibs(self):
        self.windowMadLibs = Tk()
        self.windowMadLibs.title("Mad Libs")
        self.windowMadLibs.geometry("200x200")
        frame = Frame(self.windowMadLibs)
        frame.pack()
        Label(frame, text = "\nMad Libs\n________\n").grid(row = 1, column = 1)
        Button(frame, text = "Snow Day", command = self.snowDay).grid(row = 2, column = 1)
        self.windowMadLibs.mainloop()

1 Ответ

0 голосов
/ 09 июля 2020

Основная проблема заключается в том, что он не ожидает ввода пользователя, поэтому он в основном проходит через l oop со всеми пустыми значениями в записи, а затем ничего не заполняется. (Подробнее см. Мои комментарии в коде)

Результат bound method StringVar.get - от wordInputs.append(word.get) вместо wordInputs.append(word.get())

Кроме того, несколько вызовов Tk() и .mainloop()

Это снова запустит процесс, но необходимо будет изменить размер окна,

Печатные ссылочные переменные, которые необходимо будет заполнить , вы можете захотеть dictionary вместо list:

from tkinter import *

class Game:
    #Gets user input for a specified type of word
    def getWord(self, words):           
        wordInputs = []
        for i in range(len(words)):
            frame = Frame(self.windowSnowDay)
            frame.pack()
            Label(frame, text = "\nSnow Day\n________\n").grid(row = 1, column = 1, columnspan = 2)
            Label(frame, text = "Enter a(n) " + words[i] + ":").grid(row = 2, column = 1)
            word = StringVar()
            entry = Entry(frame)
            entry.grid(row = i + 2, column = 2)
            button = Button(frame, text = "Done", command = lambda: word.set(entry.get()))
            button.grid(row = i + 3, column = 2)
            button.wait_variable(word) # waits for button to be activated and sets the variable.
            wordInputs.append(word.get())
            frame.destroy()
        return wordInputs

    #Executes "Snow Day" story from Mad Libs menu
    def snowDay(self):
        self.windowMadLibs.withdraw() # withdraw the main window.
        self.windowSnowDay = Toplevel(self.windowMadLibs) # create a Toplevel instead of a new main.
        self.windowSnowDay.title("Snow Day")
        self.windowSnowDay.geometry("200x200")
        frame = Frame(self.windowSnowDay)
        frame.pack()
        #Collects words and stores them in a list
        words = ["verb", "electronic device", "public place", "adjective", "verb ending with -ing", "color", "noun", "noun", "drink", \
            "clothing item", "adjective", "3-dimensional shape", "adjective", "plural noun", "adjective", "feeling (adjective)", "food"]
        wordInputs = self.getWord(words)
        print(wordInputs)
        #Prints "Snow Day" story with all inputted words
        print("\nAll the children cheer in", emotion, "as they", verb, "that morning. They hear on the", device,"that the", place, end =' ')
        print("is closed because of a snowstorm. They think of all the", adj, "things they could do today, such as", verb1, "on a", end = ' ')
        print(color, noun + ". Maybe they can even make a snow" + noun1 + "! They go inside, where a warm cup of", drink, "awaits", end = ' ')
        print("them. Before going outside, they put on their scarves and", clothing, "so that they don't get", adj1 + ". They", end = ' ')
        print("make a snow" + noun1, "out of 3 large", shape + "s, but it quickly fell apart because the snow wasn't very", adj2, end = '. ')
        print("After that, one of the", noun2, "attacked another, and it turned into a", adj3, "snowball fight. They were so", feeling, end = ' that ')
        print("they went straight to bed. Oh well, I guess they can eat the leftovers of Mom's famous", food, "tomorrow!")

    #Main function for Mad Libs
    def madLibs(self):
        self.windowMadLibs = Tk()
        self.windowMadLibs.title("Mad Libs")
        self.windowMadLibs.geometry("200x200")
        frame = Frame(self.windowMadLibs)
        frame.pack()
        Label(frame, text = "\nMad Libs\n________\n").grid(row = 1, column = 1)
        Button(frame, text = "Snow Day", command = self.snowDay).grid(row = 2, column = 1)
        self.windowMadLibs.mainloop()

g = Game()
g.madLibs()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...