kacper19990 kacper19990 - 3 months ago 48
Python Question

TTK, Buttons only have one number on them

import tkinter
from tkinter import ttk

def main():
root = tkinter.Tk()
numpad = NumPad(root)
root.mainloop()

numbers = [
'7', '8', '9',
'4', '5', '6',
'1', '2', '3']


class NumPad(ttk.Frame):
def __init__(self, root):
ttk.Frame.__init__(self, root)
self.grid()
self.num()

def num(self):
for c in range(1,4):
for r in range(3):
for b in numbers:
cmd = lambda b=b: print(b)
self.b= ttk.Button(self, text=b, command=cmd).grid(row = r, column = c, pady = 5)
#print(b)

main()


I'm having an issue with this code, as when I try to run it all the buttons only have 3 on them, and the only output is 3. I tried looking at what I did wrong, but still can't find the error. It only picks the last number that is in the "Numbers" function.

Any help is appreciated.

Answer

You are overriding self.b in the last inner loop. Try this:

import tkinter
from tkinter import ttk

def main():
    root = tkinter.Tk()
    numpad = NumPad(root)
    root.mainloop()

numbers = [
'7',  '8',  '9',
'4',  '5',  '6',
'1',  '2',  '3']


class NumPad(ttk.Frame):
    def __init__(self, root):
        ttk.Frame.__init__(self, root)
        self.grid()
        self.num()

    def num(self):
        for c in range(3):
            for r in range(3):
                text = numbers[c*3+r]
                cmd = lambda text=text: print(text)
                self.b= ttk.Button(self, text=text, command=cmd).grid(row = r, column = c, pady = 5)

main()