Search code examples
pythontkintertkinter-button

Tkinter button not showing text


I have a program in which I can launch another program from a menubar. When I launch that program, the buttons have no label, but are functional and the background color of them can be changed. If I start the program regularly, the labels are shown. Is there a way to fix this issue?

def create_buttons(self, w):
    for i in self.buttons: # self.buttons is an empty list when started, this is because you can change the amount of buttons in the program
        i.grid_forget()

    self.buttons = []
    self.button_vars = []

    k = 0
    for i in range(w):
        for j in range(w):
            button_var = tk.IntVar()
            button_var.set(0)
            self.button_vars.append(button_var)
            
            button = tk.Button(self.button_canvas, textvariable=self.button_vars[k], command=lambda c=k: self.button_vars[c].set(self.button_vars[c].get() + 1), width=5, height=3)
            
            button.bind("<Button-2>", lambda e, c=k: self.button_vars[c].set(self.button_vars[c].get() - 1))
            button.bind("<Button-3>", lambda e, c=k: self.button_vars[c].set(self.button_vars[c].get() - 1))
            button.grid(row=i, column=j)
            
            self.buttons.append(button)

            k += 1

This is the function I am running from the menu bar in order to launch the program:

def execute():
    App()

The init function of the App class:

def __init__(self):
    super().__init__()

    self.root = tk.Tk()
    
    self.buttons = []
    self.button_vars = []
    self.button_canvas = tk.Canvas(self.root)
    
    self.create_buttons(3)
    
    self.button_canvas.grid(row=0, column=0)
    
    self.separate_label = tk.Label(self.root, text=" ", width=1)
    self.separate_label.grid(row=1, column=0)
    
    self.size_button_frame = tk.Frame(self.root)
    
    self.size_button_3x3 = tk.Button(self.size_button_frame, text="3x3", command=lambda: self.create_buttons(3))
    self.size_button_5x5 = tk.Button(self.size_button_frame, text="5x5", command=lambda: self.create_buttons(5))
    
    self.size_button_3x3.grid(row=0, column=0)
    self.size_button_5x5.grid(row=0, column=1)
    
    self.size_button_frame.grid(row=2, column=0)
    
    self.root.mainloop()

Solution

  • The solution was to replace the tk.Tk call with tk.Toplevel instead.