Skip to content
Advertisement

Setting row of multiple buttons created by for loop with tkinter

I am trying my hand at making a GUI with tkinter and so far I’ve been successful. I need to make 4 buttons appear in my window I’ve created and i’ve placed them using .grid(). Their column is the same so it’s not a problem but I don’t know how to set their different rows much cleaner.

I have typed this which works but I know it could be done better than manually setting the rows and columns:

testbutton = Button(root, text="TEST", command=starttest)
testbutton.grid(row=16, column=19)
testbutton.config(height=4, width=20)

resultat1 = Button(root, text="Resultat 1", command=lambda: opentext("1"))
resultat1.grid(row=2, column=19)
resultat1.config(height=4, width=20)

resultat2 = Button(root, text="Resultat 2", command=lambda: opentext("2"))
resultat2.grid(row=4, column=19)
resultat2.config(height=4, width=20)

resultat3 = Button(root, text="Resultat 3", command=lambda: opentext("3"))
resultat3.grid(row=8, column=19)
resultat3.config(height=4, width=20)

I have taken a different approach like the title says using a for loop and have gotten to this point:

def start():
    buttons = []
    for i in range(4):
        button = Button(root, command=lambda i=i: printtest(i))
        button.grid(column=19)
        button.config(height=4, width=20)

def printtest(i):
        print("test ok")
start()

col_count, row_count = root.grid_size()

for col in range(col_count):
    root.grid_columnconfigure(col, minsize=31)

for row in range(row_count):
    root.grid_rowconfigure(row, minsize=31)

root.mainloop()

Is what I want to do is possible and if it can, how can I do it?

Advertisement

Answer

I do something like this

#!/usr/bin/python3
import sys
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox


class App(tk.Tk):
    """Application start here"""
    def __init__(self):
        super().__init__()

        self.protocol("WM_DELETE_WINDOW", self.on_close)
        self.resizable(width=False, height=False)
        self.title("Simple App")
        self.text = tk.StringVar()
        self.init_ui()


    def cols_configure(self, w):

        w.columnconfigure(0, weight=0,  minsize=80)
        w.columnconfigure(1, weight=0)
        
        w.rowconfigure(0, weight=0, minsize=50)
        w.rowconfigure(1, weight=0,)        

    def init_ui(self):
        
        w = ttk.Frame(self, padding=8)
        self.cols_configure(w)
       
        r = 0
        c = 1
        ttk.Label(w, text="Resultat 1").grid(row=r, sticky=tk.W)
        self.Resultat1 = ttk.Entry(w, justify=tk.CENTER,)
        self.Resultat1.grid(row=r,
                          column=c,
                          sticky=tk.W,
                          padx=5, pady=5)

        r +=1
        ttk.Label(w, text="Resultat 2").grid(row=r, sticky=tk.W)
        self.Resultat2 = ttk.Entry(w, justify=tk.CENTER,)
        self.Resultat2.grid(row=r,
                          column=c,
                          sticky=tk.W,
                          padx=5, pady=5)


        r +=1
        ttk.Label(w, text="Resultat 3").grid(row=r, sticky=tk.W)
        self.Resultat3 = ttk.Entry(w, justify=tk.CENTER,)
        self.Resultat3.grid(row=r,
                          column=c,
                          sticky=tk.W,
                          padx=5, pady=5)
        

        r = 0
        c = 2
        
        b = ttk.LabelFrame(self, text="", relief=tk.GROOVE, padding=5)
    
        bts = [("TEST", 0, self.on_callback, "<Alt-t>"),
               ("Resultat 1", 1, self.on_callback, "<Alt-r>"),
               ("Resultat 2", 2, self.on_callback, "<Alt-e>"),
               ("Resultat 3", 4, self.on_callback, "<Alt-u>"),
               ("Close", 0, self.on_close, "<Alt-c>")]

        for btn in bts:
            ttk.Button(b, text=btn[0], underline=btn[1], command = btn[2]).grid(row=r,
                                                                                column=c,
                                                                                sticky=tk.N+tk.W+tk.E,
                                                                                padx=5, pady=5)
            self.bind(btn[3], btn[2])
            r += 1
            
        b.grid(row=0, column=1, sticky=tk.N+tk.W+tk.S+tk.E)
        w.grid(row=0, column=0, sticky=tk.N+tk.W+tk.S+tk.E)

        
    def on_callback(self, evt=None):

        print("on_callback")
        
               
    def on_close(self,evt=None):
        """Close all"""
        if messagebox.askokcancel(self.title(), "Do you want to quit?", parent=self):
            self.destroy()

def main():

    app = App()
    app.mainloop()

if __name__ == '__main__':
    main()            
    

enter image description here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement