The aim of my code is that the LabelFrame-line
expands with the window. I already looked up several different solutions that work alone but not within the class I want to use.
The following is the code I wish to adapt (Code_1):
import tkinter as tk
class window(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
# LabelFrame
self.group = tk.LabelFrame(self, text="My first Label Frame")
self.group.pack(expand="yes", fill="both")
# Label inside LabelFrame
self.label = tk.Label(self.group, text="Hello")
self.label.pack()
root = tk.Tk()
app = window(root)
app.mainloop()
It gives me this Result: Result_Code_1
And this is the code that is working alone (Code_2):
import tkinter as tk
root = tk.Tk()
labelframe = tk.LabelFrame(root, text="This is a LabelFrame")
labelframe.pack(fill="both", expand="yes")
left = tk.Label(labelframe, text="Inside the LabelFrame")
left.pack()
root.mainloop()
Question: What is causing the difference of behaviour between Code_1 and Code_2 and how can I modify Code_1 to act the same way as Code_2 does?
Because the first one is inside a frame which is inside the root window itself. But the second one is directly inside the root window without being inside any container widget:
class window(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
This means your widgets will inherit from the Frame
widget as long as you make their parents self
.
Add a Frame
widget to your second code (whose parent is root
) and make this the parent of the LabelFrame
widget:
frm = tk.Frame(root)
frm.pack()
labelframe = tk.LabelFrame(frm, text="This is a LabelFrame")
labelframe.pack(fill="both", expand="yes")
Now you are getting the same view with the first code.
And in order to make Code_1 to act the same way as Code_2 does: Change this:
class window(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
to this:
class window(tk.Frame):
def __init__(self, master):
self.master = master
And change this:
self.group = tk.LabelFrame(self, text="My first Label Frame")
to this:
self.group = tk.LabelFrame(master, text="My first Label Frame")
Also, change: app.mainloop()
to: root.mainloop()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.