我正在創建一個 Tkinter/Python3 應用程式,其中主視窗繼承自Notebook(我需要選項卡),并且每個選項卡都應該是繼承自的自定義類Frame(然后我將動態地使用它matplotlib來創建自定義圖形)。不幸的是,我似乎無法Notebook接受我的習慣Frames。遵循非常簡化的代碼片段:
#!/usr/bin/env python3
from tkinter import *
from tkinter.ttk import Notebook
class MyFrame1(Frame):
def __init__(self, master=None, mytext=""):
super().__init__(master)
self.create_widgets(mytext)
def create_widgets(self, mytext):
self.label = Label(self.master, text=mytext, anchor=W)
# this is not placed relative to the Frame, but to the
# master
# 1. How I get the relative coordinates inside the frame
# to be 10, 10 of the frame area?
self.label.place(x=10, y=10, width=128, height=24)
class MyNotebook(Notebook):
def __init__(self, master=None):
super().__init__(master)
self.create_widgets()
def create_widgets(self):
self.f1 = MyFrame1(self, "abc")
# once the UI is drawn, the label "def" seems to overlay
# "abc" even when "f1" is selected
# 2. Why is self.f2 always shown even when self.f1 is
# selected?
self.f2 = MyFrame1(self, "def")
self.add(self.f1, text="f1")
self.add(self.f2, text="f2")
# Without this command nothing gets drawn
# 3. Why is this? Is this equivalent of 'pack' but for
# pixel driven layout?
self.place(width=640, height=480)
def main():
root = Tk()
root.minsize(640, 480)
root.geometry("640x480")
app = MyNotebook(master=root)
# this works as intended the label is indeed placed
# in the frame at 10, 10
#app = MyFrame1(master=root, mytext="123abc")
app.mainloop()
return None
if __name__ == "__main__":
main()
根據評論,我有以下主要問題:為什么我的自定義實體沒有MyFrame1正確顯示在里面MyNotebook?
子問題:
place當我的元素(在本例中為 a )時,如何獲得框架所在位置的相對坐標區域Label?- 為什么即使
self.f1在 UI 中選擇了選項卡,我仍然可以看到self.f2選項卡的內容? - 是否
self.place需要在不使用時顯示所有子元素pack? - 如果我在初始化后動態創建 Tkinter 元素
MyNotebook,它們會系結到相應的選項卡嗎?
不知道我做錯了什么?
謝謝!
uj5u.com熱心網友回復:
不知道我做錯了什么?
您的create_widgets方法需要將小部件添加到self,而不是self.master.
放置元素(在本例中為標簽)時,如何獲取框架所在位置的相對坐標區域?
我不明白你這是什么意思。當您使用 時place,坐標將相對于框架進行解釋。但是,我強烈建議不要使用place. 兩者都pack將grid觸發框架調整大小以適應其子級,這幾乎總是會產生回應更快的 UI
為什么即使在 UI 中選擇了 self.f1 選項卡,我仍然可以看到 self.f2 選項卡的內容?
因為您將內部小部件添加到self.master而不是self.
不使用包時是否需要 self.place 才能顯示所有子元素?
不,必須使用幾何管理器,但不一定非要使用place. 通常,place是最不希望使用的幾何管理器。pack并且grid幾乎總是更好的選擇,除了一些非常特殊的情況。
如果我在 MyNotebook 初始化后動態創建 Tkinter 元素,這些元素會系結到相應的選項卡嗎?
它們將位于您放入的任何選項卡中。
最后,我建議你洗掉self.place. create_widgets而是在創建該類實體的同一代碼塊中呼叫pack、place或。grid
小部件將自己添加到另一個小部件的布局中是一種不好的做法。創建小部件的代碼應該是將小部件添加到布局的代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/490120.html
標籤:Python python-3.x tkinter 标签 框架
下一篇:為什么這種碰撞不能正常作業?
