Search code examples
pythonpython-3.xtkintertkinter-canvastkinter-text

How to display text on a new window Tkinter?


I've started learning Tkinter on Python few weeks ago and wanted to create a Guess Game. But unfortunately I ran into a problem, with this code the text for the rules ( in the function Rules; text='Here are the rules... ) doesn't appear on the window ( rule_window).


window = Tk()
window.title("Guessing Game")

welcome = Label(window,text="Welcome To The Guessing Game!",background="black",foreground="white")
welcome.grid(row=0,column=0,columnspan=3)

def Rules():
   rule_window = Tk()
   rule_window = rule_window.title("The Rules")
   the_rules = Label(rule_window, text='Here are the rules...', foreground="black")
   the_rules.grid(row=0,column=0,columnspan=3)
   rule_window.mainloop()

rules = Button(window,text="Rules",command=Rules)
rules.grid(row=1,column=0,columnspan=1)

window.mainloop() 

Does anyone know how to solve this problem?


Solution

  • In your code you reset whatever rule_window is to a string (in this line: rule_window = rule_window.title(...))

    Try this:

    from import tkinter *
    
    window = Tk()
    window.title("Guessing Game")
    
    welcome = Label(window, text="Welcome To The Guessing Game!", background="black", foreground="white")
    welcome.grid(row=0, column=0, columnspan=3)
    
    def Rules():
       rule_window = Toplevel(window)
       rule_window.title("The Rules")
       the_rules = Label(rule_window, text="Here are the rules...", foreground="black")
       the_rules.grid(row=0, column=0, columnspan=3)
    
    rules = Button(window, text="Rules", command=Rules)
    rules.grid(row=1, column=0, columnspan=1)
    
    window.mainloop()
    

    When you want to have 2 windows that are responsive at the same time you can use tkinter.Toplevel().