7

我创建了一个按钮,并设置了它的回调,但是我怎样才能得到按钮的属性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()

我只想当我单击蓝色按钮时它会告诉我它是蓝色的。

4

3 回答 3

21

每个小部件都有一个名为的方法cget,您可以使用它来获取配置的值:

print("the foreground of bluebutton is", bluebutton.cget("fg"))
于 2013-11-14T12:32:27.067 回答
9

晚了一年多,但我认为这是要求的:

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

于 2016-09-30T20:29:29.970 回答
1

我想,Lellansin 要求这个:

 def callback(event):
    obj=event.widget
    name=str(obj)
    print("the foreground of %s is %s" %(name,obj.cget("fg")))
于 2014-07-29T06:20:21.863 回答