Home > Blockchain >  tk.Button - Assign variable to an instance spawned by tk.Button(command)
tk.Button - Assign variable to an instance spawned by tk.Button(command)

Time:01-07

Can someone please explain how I can assign a variable name to a tk.Button command that spawns a class instance? Currently stuck at..

   times_button=tk.Button(master,text="NEW",command=newToplevelWindow)

In my head I am looking for something like (pardon the syntax)..

   times_button=tk.Button(master,text="NEW",command=newWindowInstance = newToplevelWindow())

My goal is to have a series of buttons on a root window that once clicked will create a new instance of the tk.Toplevel() class which I can then play around with and tailor.

  1. Press one of the new window buttons
  2. Create newWindowInstance
  3. Call methods on that newly created instance i.e newWindowInstance.geometry("AxB")

CodePudding user response:

Button commands don't return anything (or more accurately, the code that runs the button command ignores whatever the command returns).

Unless there is a really compelling reason to do otherwise, it's best to have your buttons call a regular function or method. It makes writing, reading, debugging, and maintaining the code easier.

def createNewToplevelWindow():
    global newWindowInstance
    newWindowInstance = newToplevelWindow()

times_button=tk.Button(master,text="NEW",command=createNewToplevelWindow)
  •  Tags:  
  • Related