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