Home > Software design >  initial values applied to listbox did not appear as expected
initial values applied to listbox did not appear as expected

Time:08-08

I am working with python 3.8, macOS Big Sur.

class GUI(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.root = tk.Tk()
        self.root.title('title')
        self.root.geometry("300x100 630 80")
        self.interface()

    def interface(self):
        LIST = ["Go", "Python", "Java", "Dart", "JavaScript"]

        var = tk.StringVar()
        var.set(LIST)
        lb = tk.Listbox(self.root, listvariable=var, selectmode=tk.BROWSE)
        # var.set(LIST)
        print('var.get()', var.get())
        lb.pack(padx=10, pady=10)

if __name__ == '__main__':
    gui = GUI()
    gui.root.mainloop()

if you run the scripts above, you will get: enter image description here

however,

from tkinter import *

root = Tk()

list_var = StringVar()
list_var.set(["Go", "Python", "Java", "Dart", "JavaScript"])

# LIST = ["Go", "Python", "Java", "Dart", "JavaScript"]

Listbox(root, listvariable=list_var, selectmode=BROWSE).pack()

root.mainloop()

enter image description here

I did not get where the bug is in the first pargraph of code. From my opinion, they're almost the same. The only difference is that the 1st paragraph of code is packed as a class.

CodePudding user response:

You get two tk.Tk() when initializing the GUI. GUI is the subclass of tk.Tk, so only super().__init__() ok, self.root = tk.Tk() will initiate another Tk.

import tkinter as tk

class GUI(tk.Tk):

    def __init__(self):
        super().__init__()
        # self.root = tk.Tk()
        self.title('title')
        self.geometry("300x100 630 80")
        self.interface()

    def interface(self):
        LIST = ["Go", "Python", "Java", "Dart", "JavaScript"]

        var = tk.StringVar()
        var.set(LIST)
        lb = tk.Listbox(self, listvariable=var, selectmode=tk.BROWSE)
        # var.set(LIST)
        print('var.get()', var.get())
        lb.pack(padx=10, pady=10)

if __name__ == '__main__':
    gui = GUI()
    gui.mainloop()
  • Related