如何使用 tkinter 将列表框添加到我的代码中

How can I add Listbox using tkinter to my code

如何使用 tkinter 添加列表框到 App class 中的 create_widgets 方法? 我的问题是 "Listbox(master)" 我不知道如何将它集成到我的代码中,每次我尝试时都会出错。

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()

例如,如果我需要集成此列表框代码,我应该怎么做?

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()

您可以直接将其编辑到您的代码中吗?不明白为什么不能像拥有所有其他小部件一样集成它。

保持原来的网格结构:

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()