jaad salem jaad salem - 6 months ago 14
Python Question

How can I add Listbox using tkinter to my code

How can I add Listbox using tkinter to create_widgets method in App class?
my problem is "Listbox(master)" I don't know how to integrate it in my code and every time I try to i get an error .

from tkinter import *

class App(Frame):

def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()

def create_widgets(self):

IpLabel = Label(self, text='Device_A Ip')
IpLabel.grid(row=0, column=0)
IpEntry = Entry(self, width=20)
IpEntry.grid(row=0, column=1)
IpEntry.insert(0, '10.0.0.5')

#Checkbutton
self.var = BooleanVar()
cb = Checkbutton(self, text="Infinite Loop", variable=self.var)
cb.deselect() #the Checkbutton default is unselected
cb.grid(columnspan=2) #place of the Checkbutton


#run widget
self.run_button = Button(self, text='run')
self.run_button.grid(row=20, column=0)


def run(self):
self.mainloop()


if __name__ == "__main__":

#open gui file
root = Tk()
root.title('ACM')
app = App(root)
app.run()


for example if I need to integrate this listbox code what should I do?

master = Tk()

listbox = Listbox(master)
listbox.pack()

listbox.insert(END, "a list entry")

for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)

mainloop()

Answer

You can just edit it into your code? Not seeing why you can't just integrate this like you have all your other widgets.

Keeping your original grid structure:

import tkinter as tk

class App(tk.Frame):

    def __init__(self, master):

        tk.Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):

        IpLabel = tk.Label(self, text='Device_A Ip')
        IpLabel.grid(row=0, column=0)
        IpEntry = tk.Entry(self, width=20)
        IpEntry.grid(row=0, column=1)
        IpEntry.insert(0, '10.0.0.5')

        #Checkbutton
        self.var = tk.BooleanVar()
        cb = tk.Checkbutton(self, text="Infinite Loop", variable=self.var)
        cb.deselect() #the Checkbutton default is unselected
        cb.grid(columnspan=2) #place of the Checkbutton

        listbox = tk.Listbox(self)
        listbox.insert(tk.END, "a list entry")
        for item in ["one", "two", "three", "four"]:
            listbox.insert(tk.END, item)
        listbox.grid(row=1, rowspan=19, column=0, columnspan=2, sticky="nsew")
        #run widget
        self.run_button = tk.Button(self, text='run')
        self.run_button.grid(row=20, column=0)

if __name__ == "__main__":

    #open gui file
    root = tk.Tk()
    root.title('ACM')
    app = App(root)    
    root.mainloop()
Comments