Home > Blockchain >  Is there a way to create GUI component in Python Tkinter?
Is there a way to create GUI component in Python Tkinter?

Time:11-17

I am writing GUI in Python using Tkinter and I am having some difficulties. I have this repeatable segment:

enter image description here

It repeats 8 times.

I would like to create class or struct of:

frame1 = LabelFrame(root, text="Host 0", padx=5, pady=5)
frame1.grid(row=0, column=0)
labela1 = Label(frame1, text="ID 21")
c1 = Checkbutton(frame1, text="Save images")
c1.grid(row=2, column=1, columnspan=2)
b11 = Button(frame1, text="Start host")
b12 = Button(frame1, text="Start app")
b13 = Button(frame1, text="Kill app")
b14 = Button(frame1, text="Turn off host")
labela1.grid(row=1, column=0)
b11.grid(row=1, column=2)
b12.grid(row=1, column=3)
b13.grid(row=1, column=4)
b14.grid(row=1, column=5)
labela12 = Label(frame1, text="Status", fg='#00f')
labela12.grid(row=2, column=3, columnspan=4)

and then populate GUI through for loop. Is this possible in python? I really couldn't find anything on the web for this type of problem. Thanks in advance!

CodePudding user response:

The most common and easiest way of creating a custom widget is to start by creating a class that inherits from Frame or LabelFrame. Put anything you want inside that class. You can then use that class just like any other widget.

import tkinter as tk

class HostController(tk.LabelFrame):
    def __init__(self, parent, hostid, title):
        super().__init__(parent, text=title)
        self.hostid = hostid

        labela1 = tk.Label(self, text=f"ID {hostid}")
        c1 = tk.Checkbutton(self, text="Save images")
        c1.grid(row=2, column=1, columnspan=2)

        b11 = tk.Button(self, text="Start host")
        b12 = tk.Button(self, text="Start app")
        b13 = tk.Button(self, text="Kill app")
        b14 = tk.Button(self, text="Turn off host")

        labela1.grid(row=1, column=0)
        b11.grid(row=1, column=2)
        b12.grid(row=1, column=3)
        b13.grid(row=1, column=4)
        b14.grid(row=1, column=5)

        labela12 = tk.Label(self, text="Status", fg='#00f')
        labela12.grid(row=2, column=3, columnspan=4)

root = tk.Tk()
for i in range(5):
    hc = HostController(root, hostid=i, title=f"Host {i}")
    hc.pack(side="top", padx=4, pady=(0,4))

root.mainloop()

screenshot

  • Related