-1

I tried to create a window with a button that creates another window.

m = Tk() 

def new(a,b): 
    r = Tk()
    r.geometry(str(a) + "x" + str(b) + "+0+0")

b = Button(m, text="Click", command=new(100,300)).place(x=0,y=0)

m.mainloop()

Instead of getting a window with a button i get two without clicking the button.

The two windows.png

What did i do wrong?

Catman
  • 1
  • 1
  • @BryanOakley As the issue of the buttons command execution on init has been asked before I think a bigger problem here is the OP using `Tk()` twice causing the double windows instead of using `Toplevel` like they should be. The OPs main question is about creating a 2nd window on button press but they are doing it wrong and this should be addressed either with a good answer or a duplicate question related to using `Tk()` twice in a program. – Mike - SMT Oct 25 '17 at 14:39
  • Even if they used a `Toplevel`, they would still get two windows on startup. The reason they get two windows is because of the `command` vs `command()` thing. I agree that using `Tk()` twice is a problem, but that's not what they were asking about. – Bryan Oakley Oct 25 '17 at 16:46
  • @BryanOakley Ya there is that problem of the command vs command() I just think that the 2 part nature of this problem deserves a better explanation then just linking to only the solution to half of what is wrong here. – Mike - SMT Oct 28 '17 at 15:06

2 Answers2

0

You're calling new as you construct the Button (technically, before you construct the Button since new must finish running so its return value can be passed as the command argument), not passing it as a callback to invoke on click.

You need to pass a (no argument) callable as the command without calling it, e.g. using a lambda to wrap your new call and thereby defer it until the lambda is called:

b = Button(m, text="Click", command=lambda: new(100,300)).place(x=0,y=0)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

Inside of your Button call you're called the new function. That function is creating a new instance of Tk. This is why you have two windows opening.

Assuming you want to run the geometry operation on the first Tk instance, just pass the Tk object into your new function.

You can do it like so:

from tkinter import *

m = Tk()

def new(a, b, r):
    r.geometry(str(a) + "x" + str(b) + "+0+0")

b = Button(m, text="Click", command=new(100, 300, m)).place(x=0, y=0)

m.mainloop()
Kaiser Dandangi
  • 230
  • 2
  • 8
  • This actually does not help with the OPs question. They are wanting to open a 2nd window and should be using `Toplevel` for that inside of their function. Also you have not fixed the problem of the command running at init. – Mike - SMT Oct 25 '17 at 14:49
  • Oops you're right, I didn't read all of it. – Kaiser Dandangi Oct 28 '17 at 13:25