user9740696
user9740696

Reputation:

Python 3 - Create global Button with name from string Tkinter

Okay, so I started programming Minesweeper. For that, I need a variable number of Buttons (or should I use something different). So I got two loops which should create a button with a name. But I need the buttons of course to have other names. So f.i.: the first button = button_1 the second button = button_2 ...

My code goes so:

class test(Tk):
   def __init__(self):
      self.frame_game = Frame(self)
      for i in range(1, height):
           for j in range(1, height):
               # here i need the button to be created

I tried it with:

globals()['Button_' + str(i) + str(j)] = Button(...)

but that doesn't work because I need a button which is global.

I also tried it with

vars(self)['Button_' + str(i) + str(j)] = Button(self.frame_game, text='0').pack()

I pack the label later with:

self.frame_game.pack()

It doesn't throw an Exception.

Anyone got an idea?

EDIT: IT WORKS!!!! The code just didnt go into the loop. changed it to

for i in range(0, height):

Also of course the other loop with j. The working code is in the loop following:

vars(self)['Button_' + str(i) + str(j)] = Button(self.frame_game, text='0').pack()

Upvotes: 0

Views: 1311

Answers (2)

Mohamed Elghobary
Mohamed Elghobary

Reputation: 11

  • You can declare the global button as follows:
  • set a global variable name for the button
global myBtn
myBtn = Button(root, text = "This is a global button")

Thank you Mohamed Elghobary

Upvotes: 1

Bryan Oakley
Bryan Oakley

Reputation: 386342

You should never create variables like this. It makes your code very difficult to read, very difficult to debug.

Instead, store the widgets in a list or dictionary. Since you want to reference them by name, a dictionary works best:

self.buttons = {}
for i in range(1, height):
    for j in range(1, height):
        name = "Button_{}_{}".format(i,j)
        button = Button(...)
        button.pack()
        self.buttons[name] = button

With the above, you can later reference the buttons like self.buttons["Button_1_1"], etc.

Also, in your code you're doing something like Button(...).pack(). .pack() returns None, so you're setting all of your variables to None. If you want to save references to your buttons, you need to call pack (or grid or place) in a separate statement from where you create the button.

Upvotes: 0

Related Questions