我的應用程式有兩個檔案,在第二個檔案中我page_one.py無法正確使用錨點方法。“左”和“右”標簽始終位于螢屏中間而不是側面
# 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()
我怎樣才能使該 anchor選項起作用?
uj5u.com熱心網友回復:
那是因為你的PageOne框架沒有填滿Main。也添加fill="both"到它的pack方法中:
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()
請注意,您可以super()在init函式中使用(不self作為引數)
uj5u.com熱心網友回復:
您必須fill="both"在打包PageOne框架時指定它才能在 x 和 y 軸上完全展開。相應地更新你的main.py。
# 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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/536901.html
上一篇:每次我運行這個函式時它越來越慢
