[Python] Python Tkinter - Run window before loop

Discussão em 'Python' iniciado por Stack, Fevereiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    Background Information

    The below is the code I'm currently working on to create a program that essentially prints a word, and asks you to correctly spell the word. A word can only be printed once, as once used it is put into the usedWords dictionary so that it is not reused. When all the words have been used up, the while loop ends. This all works perfectly, however now I'm trying to integrate this with a GUI.

    What specifically my problem is

    The issue is that I would like to have the Tkinter window have a label, and have the label update every time a new word is printed out. However, I am currently getting an error AttributeError: 'NoneType' object has no attribute '_root' I believe this is happening because I have tried to add a Label before defining the main window is defined- but I have unable to do this any other way, if the window is defined before the loop the window does not open before the loop is finished, which is obviously counter-intuitive to what I want to actually do.

    With all that said- my question

    It's as simple as this- how do I make this worK? I want to create the window before the loop, and have the Label within the window update every time a new word is selected from the list

    import random
    import time
    from tkinter import *
    from tkinter.messagebox import *

    words = ['reflection', 'attitude', 'replicate', 'accomodate', 'terrain',
    'argumental', 'stipulate', 'stimulation', 'latitude', 'marginal',
    'thedubester', 'security', 'documentation', 'ukulele',
    'terminal', 'exaggeration', 'declaration', 'apptitude', 'absence',
    'aggressive', 'acceptable', ' allegiance', 'embarass', 'hierarchy',
    'humorous', 'existence']

    usedWords = []

    while len(usedWords) < len(words):
    chooseWord = words[random.randrange(len(words))]

    var = StringVar()
    display = Label(textvariable = var)
    display.place(x=1,y=1)

    if chooseWord not in usedWords:


    var.set(chooseWord)
    userSpelt = input("Spelling: ")
    usedWords.append(chooseWord)

    if userSpelt in words:
    print("Correctly spelt!")
    else:
    print("Incorrectly spelt!")



    master = Tk()
    master.geometry("500x600")
    master.title("Minesweeper V 1.0")
    master.configure(background="#2c3e50")

    Continue reading...

Compartilhe esta Página