2012-10-15 32 views
1


簡而言之:有沒有一個函數可以獲取Tkinter中的一個控件的主框架的名稱?如何獲取Tkinter中的主框架的名稱

讓我告訴你一點點:
有一個按鈕,命名爲「後退按鈕」

self.BackButton = Button(self.SCPIFrame, text = "Back", command = self.CloseFrame) 
self.BackButton.place(x = 320, y = 320, anchor = CENTER) 

當我點擊這個按鈕,有一個名爲「CloseFrame」功能,它關閉當前幀(並做一些其他的東西),在這種情況下是「SCPIFrame」。但爲此,我需要BackButton存在的Frame的名稱。 任何想法?感謝您的幫助。

回答

2

要字面上回答你的問題:

有一個函數來獲取一個小部件的 Tkinter的主框架的名稱?

winfo_parent正是你所需要的。爲了有用,您可以將它與_nametowidget結合使用(因爲winfo_parent實際上會返回父級的名稱)。

parent_name = widget.winfo_parent() 
parent = widget._nametowidget(parent_name) 
+0

當我嘗試打印BackButton的父名稱,我得到一個數字: .33500616。 'self.parent_name = self.BackButton.winfo_parent()' 'print self.parent_name' – eljobso

+0

此編號是Tcl變量名稱。 '_nametowidget'檢索相應的Tkinter實例。說到**對象的**名稱有點可疑,因爲許多變量都可以綁定到這個對象。但是,我們在Tcl之上的Tkinter間接提供了一個唯一的_name_作爲Tcl變量名的情況。 – FabienAndre

1

如果使用面向對象的編程風格,則主框架既可以是對象本身,也可以是對象的屬性。例如:

class MyApplication(tk.Tk): 
    ... 
    def close_frame(self): 
     # 'self' refers to the root window 

另一種簡單的方式在非面向對象的方式來解決這個問題是要麼存儲主在全局窗口(正常工作非常小的程序,但不建議任何將必須隨時間推移),或者您可以將它傳遞給回調。例如:

self.BackButton = Button(..., command=lambda root=self.SCPIFrame: self.close_frame(root)) 
... 
def CloseFrame(self, root): 
    # 'root' refers to whatever window was passed in 
1

我認爲最好的方法是使用的.master屬性,這實際上是主人的實例:) 例如(我在IPython都這樣做):

import Tkinter as tk 

# We organize a 3-level widget hierarchy: 
# root 
# frame 
#  button 

root = tk.Tk() 
frame = tk.Frame(root)  
frame.pack() 
button = tk.Button(frame, text="Privet!", background='tan') 
button.pack() 

# Now, let's try to access all the ancestors 
# of the "grandson" button: 

button.master # Father of the button is the frame instance: 
<Tkinter.Frame instance at 0x7f47e9c22128> 

button.master.master # Grandfather of the button, root, is the frame's father: 
<Tkinter.Tk instance at 0x7f47e9c0def0> 

button.master.master.master # Empty result - the button has no great-grand-father ;)