How can I accommodate things in tkinter?

Viewed 52

im trying to learn python and i thought on make a piano, i started to create it with tkinter, but i dont find the way to arrange the buttons like a piano this is my code:

import tkinter as tk
ventana = tk.Tk()
ventana.geometry("360x240")

label1 = tk.Label()
label1['text'] = "Piano"
label1.pack()


btn_C = tk.Button(ventana, text='C', width=3, height=10)
btn_C.pack()

btn_Db = tk.Button(ventana, text='Db', width=3, height=10)
btn_Db.pack()

btn_E = tk.Button(ventana, text='E', width=3, height=10)
btn_E.pack()

ventana.mainloop()

I also thought that I could create all the buttons with a loop or something like that, if someone could explain me how I would appreciate it very much.

English is not my language, sorry if there is any mistake :p

2 Answers

If I understand correctly you want all the buttons on the same horizontal line. This should get you what you want.

import tkinter as tk
ventana = tk.Tk()
ventana.geometry("360x240")

label1 = tk.Label()
label1['text'] = "Piano"
label1.pack()

btn_C = tk.Button(ventana, text='C', width=3, height=10)
btn_C.pack(side='left')

btn_Db = tk.Button(ventana, text='Db', width=3, height=10)
btn_Db.pack(side='left')

btn_E = tk.Button(ventana, text='E', width=3, height=10)
btn_E.pack(side='left')

ventana.mainloop()

One option would be adding the items using a for loop with side=tk.LEFT option of .pack

l=['C','Dd','E']
for b in l:
    btn_b = tk.Button(ventana, text=b, width=3, height=10).pack(side=tk.LEFT)

or even one line as

btn_b = [ tk.Button(ventana, text=b, width=3, height=10).pack(side=tk.LEFT) for b in ['C','Dd','E'] ]
Related