I've two file for my app, and in my second one page_one.py
I can't use properly the anchor method. The label 'left' and 'right' are always positioned in the middle of the screen and not on the side
# main.py
import tkinter as tk
from page_one import PageOne
class Main(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.page_one = PageOne(self)
self.page_one.pack(expand='True')
if __name__ == "__main__":
root = tk.Tk()
main = Main(root)
root.attributes("-fullscreen", True)
main.pack(side="top", fill="both", expand=True)
root.mainloop()
# page_one.py
import tkinter as tk
class PageOne(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.one_label = tk.Label(self, text='LEFT')
self.one_label.pack(padx=(20,0), side='left', anchor='w')
self.two_label = tk.Label(self, text='RIGHT')
self.two_label.pack(padx=(0,20), side='right', anchor='e')
if __name__ == "__main__":
root = tk.Tk()
PageOne(root).pack(side="top", fill="both", expand=True)
root.mainloop()
How can I make the anchor
option works?
CodePudding user response:
That's because your PageOne
frame doesn't fill Main
. Add fill="both"
to its pack
method as well:
import tkinter as tk
class PageOne(tk.Frame):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.one_label = tk.Label(self, text='LEFT')
self.one_label.pack(padx=(20,0), side='left', anchor='w')
self.two_label = tk.Label(self, text='RIGHT')
self.two_label.pack(padx=(0,20), side='right', anchor='e')
class Main(tk.Frame):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.page_one = PageOne(self)
self.page_one.pack(expand='True', fill="both")
if __name__ == "__main__":
root = tk.Tk()
main = Main(root)
#root.attributes("-fullscreen", True)
root.geometry("1280x720")
main.pack(side="top", fill="both", expand=True)
root.mainloop()
Note that you can use super()
in your init
functions (without self
as argument)
CodePudding user response:
You have to specify fill="both"
when packing the PageOne
frame for it to expand completely in the x and y axis. Update your main.py
accordingly.
# main.py
import tkinter as tk
from page_one import PageOne
class Main(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.page_one = PageOne(self)
self.page_one.pack(fill="both", expand='True')
if __name__ == "__main__":
root = tk.Tk()
main = Main(root)
root.attributes("-fullscreen", True)
main.pack(side="top", fill="both", expand=True)
root.mainloop()