簡體   English   中英

如何獲得 Tkinter 小部件屬性?

[英]How can I get a Tkinter widget attribute?

我創建了一個 Button,並設置了它的回調,但是如何獲得像fg這樣的按鈕的屬性?

from Tkinter import *

def callback(self):
    tkMessageBox.showinfo("button", color)

top = Tk()
frame = Frame(top)
frame.pack()

greenbutton = Button(frame, text="Brown", fg="brown", command=callback)
greenbutton.pack( side = RIGHT )

bluebutton = Button(frame, text="Blue", fg="blue", command=callback)
bluebutton.pack( side = LEFT )

top.mainloop()

我只想當我點擊藍色按鈕時它會告訴我它是藍色的。

每個小部件都有一個名為cget的方法,您可以使用它來獲取配置值:

print("the foreground of bluebutton is", bluebutton.cget("fg"))

晚了一年多,但我認為這是要求的:

import tkinter as tk


class GetWidgetAttributes:
    @staticmethod
    def get_attributes(widget):
        widg = widget
        keys = widg.keys()
        for key in keys:
            print("Attribute: {:<20}".format(key), end=' ')
            value = widg[key]
            vtype = type(value)
            print('Type: {:<30} Value: {}'.format(str(vtype), value))


if __name__ == '__main__':
    gw = GetWidgetAttributes()
    # For Example, find all attributes of Tkinter Frame
    gw.get_attributes(tk.Frame())

結果是:

Attribute: bd                   Type: <class 'int'>                  Value: 0
Attribute: borderwidth          Type: <class 'int'>                  Value: 0
Attribute: class                Type: <class 'str'>                  Value: Frame
Attribute: relief               Type: <class 'str'>                  Value: flat
Attribute: background           Type: <class 'str'>                  Value: SystemButtonFace
Attribute: bg                   Type: <class 'str'>                  Value: SystemButtonFace
Attribute: colormap             Type: <class 'str'>                  Value: 
Attribute: container            Type: <class 'int'>                  Value: 0
Attribute: cursor               Type: <class 'str'>                  Value: 
Attribute: height               Type: <class 'int'>                  Value: 0
Attribute: highlightbackground  Type: <class 'str'>                  Value: SystemButtonFace
Attribute: highlightcolor       Type: <class 'str'>                  Value: SystemWindowFrame
Attribute: highlightthickness   Type: <class 'int'>                  Value: 0
Attribute: padx                 Type: <class '_tkinter.Tcl_Obj'>     Value: 0
Attribute: pady                 Type: <class '_tkinter.Tcl_Obj'>     Value: 0
Attribute: takefocus            Type: <class 'str'>                  Value: 0
Attribute: visual               Type: <class 'str'>                  Value: 
Attribute: width                Type: <class 'int'>                  Value: 0

拉茲60p

我想,萊蘭辛是在要求這個:

 def callback(event):
    obj=event.widget
    name=str(obj)
    print("the foreground of %s is %s" %(name,obj.cget("fg")))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM