0

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.

missmango
  • 105
  • 2
  • 9

1 Answers1

0

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()
Jason Yang
  • 11,284
  • 2
  • 9
  • 23
  • your example code did work. but I speculate that even I initialized two Tk, I 've given self.root to tk.Listbox as its master, at least it is supposed to appear in the root window? – missmango Aug 08 '22 at 12:03
  • Maybe there should be only one `Tk()`, you can refer https://stackoverflow.com/a/48045508/11936135 – Jason Yang Aug 08 '22 at 12:29