Skip to content
Advertisement

I cannot redirect in tkinter program

My aim is to open on the same window when the button is pressed. But when I run the program, it opens in 2 windows at the same time.

I want it to open when the button is pressed.

How can I do it?

import tkinter as tk
from tkinter import messagebox
 
master = tk.Tk()
uruns = tk.Tk()

master.geometry("300x300")
uruns.geometry("300x300")
 
def buttonCallback():
    mas = master.Label(uruns, text="Urunler listesi")
    mas.pack()
 
urunler = tk.Button(master, text="Click", command=buttonCallback)
 
label_1 = tk.Label(master, text="Bolat Aktar ürün yönetim sistemi")
 
# Use the grid geometry manager to put the widgets in the respective position
label_1.grid(row=0, column=0)
urunler.grid(row=1, column=0)

 
# The application mainloop
tk.mainloop()

Advertisement

Answer

Your Problem is pretty easy. you cant do twice Tk() in your code and any tkinter code should be have one Tk(). so if you want to make another window you will need Toplevel() it’s the same as Tk(). so there are 2 methods to do this:

Method 1 make a Toplevel() in the function:

so you want to open a new window with that button right ? and you dont want to run twice windows in the beginning.

  1. delete your uruns = tk.Tk()

  2. in your function buttonCallBack do this:

def buttonCallBack:
    uruns = tk.Toplevel()
    uruns .geometry("300x300")
    mas   = tk.Label(uruns, text="Urunler listesi")
    mas   .pack()

the full code:

import tkinter as tk
from tkinter import messagebox
 
master = tk.Tk()
master.geometry("300x300")
 
def buttonCallback():
    uruns  = tk.Toplevel()
    uruns  .geometry("300x300")
    mas    = Label(uruns, text="Urunler listesi")
    mas    .pack()
 
urunler = tk.Button(master, text="Click", command=buttonCallback)
 
label_1 = tk.Label(master, text="Bolat Aktar ürün yönetim sistemi")
 
# Use the grid geometry manager to put the widgets in the respective position
label_1.grid(row=0, column=0)
urunler.grid(row=1, column=0)

 
# The application mainloop
master.mainloop()

Method 2(the best) show/hide your another window Toplevel():

to show your Toplevel() use Toplvel.deiconify()

to hide your Toplevel() use Toplvel.withdraw ()

so do this:

import tkinter as tk
from tkinter import messagebox

master = tk.Tk()
uruns  = tk.Toplevel()

uruns  .withdraw() # Hide the second window

uruns  .geometry("300x300")
master .geometry("300x300")

def buttonCallback():

    uruns .deiconify() # Show the second window

    mas   = tk.Label(uruns, text="Urunler listesi")
    mas   .pack()

urunler = tk.Button(master, text="Click", command=buttonCallback)

label_1 = tk.Label(master, text="Bolat Aktar ürün yönetim sistemi")

# Use the grid geometry manager to put the widgets in the respective position
label_1.grid(row=0, column=0)
urunler.grid(row=1, column=0)

# The application mainloop
master.mainloop()
Advertisement