0

I'm using Tkinter and i want to create a lot of windows but, each one with a different object name so i can move them individually.

Example:

def window(self):
        
        self.window1 = Tk()

        sizexcenter = str(int(self.root.winfo_screenwidth() / 2 - 20))
        sizeycenter = str(int(self.root.winfo_screenheight() / 2 - 20))


        self.window1.geometry('40x40' + '+' + sizexcenter + '+' + sizeycenter)
        self.window1.overrideredirect(1)
        self.window1.mainloop()

And when calling this function next time

def window(self):
        
        self.window2 = Tk()

        sizexcenter = str(int(self.root.winfo_screenwidth() / 2 - 20))
        sizeycenter = str(int(self.root.winfo_screenheight() / 2 - 20))


        self.window2.geometry('40x40' + '+' + sizexcenter + '+' + sizeycenter)
        self.window2.overrideredirect(1)
        self.window2.mainloop()

And so on, is for Snake game but in windows desktop, each piece of the tail would be a window

Pedro
  • 360
  • 3
  • 13

1 Answers1

0

I have seen this question asked before in different contexts, but generally it is asking for dynamically named variables. And the answer is not specific to Tkinter. What you usually want to reach for is a dictionary.

    self.windows = {}
    self.windows['window1'] = Tk()
    self.windows['window2'] = Tk()

Yes there are ways to dynamically create variables with getattr / setattr but they really are lower level solutions for something where a dict makes perfect sense.

Update:

If you don't really care about accessing these objects randomly by name and you just want to keep creating new windows, maybe appending to a list is more suitable, as that would grow your snake and maintain order.

    self.windows = []
    self.windows.append(Tk())
    self.windows.append(Tk())

    self.windows[0].foo
    self.windows[1].bar
jdi
  • 90,542
  • 19
  • 167
  • 203