Home > Software design >  Why does tkinter creating two windows here? And how can i stop it?
Why does tkinter creating two windows here? And how can i stop it?

Time:11-07

import tkinter as tk
from subprocess import check_call



def copy_name():
    cmd = 'echo '   name.strip()   '|clip'
    return check_call(cmd, shell=True)


root = tk.Toplevel(background="black")
root.title("Copying")
root.resizable(False, False)

T = tk.Label(root, text=name, height=2, width=len(name)   25, background="black", foreground="white")
T.pack()

button = tk.Button(root, text="Copy", command=copy_name, background="black", foreground="white")
button.pack()
tk.mainloop()

This is my code.

I just wanted to test this way of copying text...

About my expectations... i want to understand from where those windows are appearing, and how to stop it. Im just a newbie in Python and Tkinter... so please, tell me what i did wrong

CodePudding user response:

Every tkinter window requires a root window - an instance of Tk. If you don't create one, one will be created automatically. When you do root = tk.Toplevel(background="black"), tkinter will first create an instance of Tk and then it will create your Toplevel, resulting in two windows.

The solution in this case is to call Tk instead of Toplevel. Also, you'll need to remove the background="black" argument and instead configure the background in a separate step.

root = tk.Tk()
root.configure(background="black")

CodePudding user response:

As @Bryan said, you should forget about Toplevel(). The normal way is Tk().
Try this:

import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk()
label = tk.Label( root, text='Select:', background='green').pack(side='top')
btn1 = ttk.Button( root, text='Discard').pack()
btn2 = ttk.Button( root, text='Quit').pack()
while True:
  root.mainloop()

And you should get: Result

  • Related