14

How would I be able to open a new window by the user pressing a button in a tkinter GUI? I only need quite simple solutions, and if the code could be explained as well that would be great.

martineau
  • 119,623
  • 25
  • 170
  • 301
Eddy Loring
  • 181
  • 1
  • 1
  • 3
  • 1
    Have you attempted to do this yourself, and if you did could you please edit your question to contain the code – tox123 Dec 24 '14 at 15:55
  • 7
    Seems like you have two questions here. "How do I make something happen in response to a button click?". Assign a function to the button's `command` attribute, or use the `bind` method. "How do I make a new window?" Use the `Toplevel` widget. – Kevin Dec 24 '14 at 15:56
  • 2
    What is the Toplevel widget? – Eddy Loring Dec 24 '14 at 16:03
  • 1
    @EddyLoring from what I understand, a `TopLevel` widget is a pop up window – tox123 Dec 24 '14 at 16:05
  • But how would I be able to use it in order to make a new window? I don't understand how to use it – Eddy Loring Dec 24 '14 at 16:07

1 Answers1

30

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685