Tkinter 中插件属性的配置方法
Reference
- http://effbot.org/tkinterbook/tkinter-widget-configuration.htm
- https://www.cnblogs.com/hupeng1234/p/6937451.html
通过设置属性来改变Widget的外观, 常见的属性包括text(显示的文字) 、color(前景色fg和背景色bg)、size(宽度和高度)、 command callbacks(点击后的回调函数)等等
[TOC]
1.设置属性,显性配置有3种方式:
1)在创建Widget时,通过关键字参数设定
widgetclass(master, option=value, …) => widget
实例:
# coding=utf-8
from Tkinter import *
def touch():
print 'button clicked'
root = Tk()
btn = Button(root, text="Touch me", fg="red", bg="blue", command=touch) # 指定显示的文本,前景色,背景色,点击后的回调函数
btn.pack()
root.mainloop()
2) 在对象创建完毕后,通过类似字典的方式,以属性为key,进行访问修改
# coding=utf-8
from Tkinter import *
def touch():
print 'button clicked'
root = Tk()
btn = Button(root, text="Touch me")
btn["fg"] = "red"
btn["bg"] = "blue"
btn['width'] = 5
btn['height'] = 5
btn["command"] = touch
btn.pack()
root.mainloop()
3)对象创建完毕后,调用config函数
# coding=utf-8
from Tkinter import *
def touch():
print 'button clicked'
root = Tk()
btn = Button(root, text="Touch me")
btn.config(fg="red", bg="blue", command=touch) #调用config函数,设置属性
btn.pack()
root.mainloop()
2. 举例:设置显示的文本
比如我们要使得,按钮按下后,按钮本身的text显示不同的内容
- 通过设置text属性
- 在创建的时候设置
- 使用字典的形式设置
- 使用config函数设置
- 通过设置textvariable
- 创建StringVar变量
- 通过set函数设置stringvar变量
import tkinter as tk
class MyTest(object):
def __init__(self, root=None):
self.window = root
self._gui_init()
def _gui_init(self):
self.text_var = tk.StringVar()
self.text_var.set("Hey, hello?")
self.label = tk.Label(self.window, width=30, height=10, textvariable=self.text_var, fg='red', bg='blue')
self.label.pack()
# 设置btn已有属性
# 方法一:在创建的时候设置 btn的text属性
self.btn1 = tk.Button(self.window, width=10, height=5, fg='#008080', bg='black', text='click me')
self.btn1['command'] = self.call_me
# 给btn添加新的属性
self.is_clicked = False
self.btn1.pack()
def call_me(self):
if not self.is_clicked:
# 方法二:通过字典的形式设置btn的text属性
self.btn1['text'] = 'reset'
self.is_clicked = True
self.text_var.set("keep away from me!")
else:
# 方法三:通过config函数设置btn的text属性
self.btn1.config(text='click me')
self.is_clicked = False
self.text_var.set("Hey, hello?")
if __name__ == '__main__':
root = tk.Tk()
root.wm_title("Methods to Set Text")
my_test = MyTest(root)
tk.mainloop()
3. 向后兼容性: 通过apply函数来设置
关键字参数在Python1.3时被引入。之前,使用原始的Python字典将选项传递给窗口构造器和configure方法。原代码类似如下: self.button = Button(frame, {“text”: ”QUIT”, ”fg”: ”red”, ”command”: frame.quit})self.button.pack({“side”: LEFT})
关键字参数语法更优雅和少容易发生错误。但是为了与存在的代码兼容,Tkinter仍支持老的语法。在新的程序中你不应再用老的语法,即使是在某些情况下是很有吸引力的。例如,如果你创建了一个定制的窗口部件,它需要沿它的父类传递配置选项,你的代码可能如下:
def __init__(self, master, **kw):
Canvas.__init__(self, master, kw) # kw 是一个字典
上面的代码在当前版本的Tkinter下工作的很好,但是它在将来的版本下可能不工作。一个办法是使用apply函数:
def __init__(self, master, **kw):
apply(Canvas.__init__, (self, master), kw)
这个apply函数使用了一个函数(一个未约束的方法),一个带参数的元组(它必须包括self,因为我们调用一个未约束的方法),一个可选的,提供了关键字参数的字典。
注意:Removes usage of
apply()
. For exampleapply(function, *args, **kwargs)
is converted tofunction(*args, **kwargs)
.i.e., 官网取消了appy方法的使用,例如,用function(* args, **kwargs) 代替了方法appy
4. 获取属性以及属性对应的值
- 获取属性: 调用Widget的keys()方法
- 同时获取属性以及对应的值: 调用Widget对应的无参config()方法
实例
# coding=utf-8
from Tkinter import *
root = Tk()
btn = Button(root, text="Touch me")
print("cget:", self.btn1.cget('text')) # 只获取button的text属性
print("Text:", btn1['text']) # 只获取button的text属性
print("attributes:\n", btn.keys()) # 只获取Button实例属性
print("key-value:\n", btn.config()) # 获取Button实例的属性和值
btn.pack()
root.mainloop()
输出:
cget: Touch me
Text: Touch me
attributes:
['activebackground', 'activeforeground', 'anchor', 'background', 'bd', 'bg', 'bitmap', 'borderwidth', 'command', 'compound', 'cursor', 'default', 'disabledforeground', 'fg', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'justify', 'overrelief', 'padx', 'pady', 'relief', 'repeatdelay', 'repeatinterval', 'state', 'takefocus', 'text', 'textvariable', 'underline', 'width', 'wraplength']
key-value:
{'highlightthickness': ('highlightthickness', 'highlightThickness', 'HighlightThickness', <pixel object at 02325330>, <pixel object at 02325330>), 'text': ('text', 'text', 'Text', '', 'Touch me'), 'image': ('image', 'image', 'Image', '', ''), 'compound': ('compound', 'compound', 'Compound', <index object at 03045250>, 'none'), 'height': ('height', 'height', 'Height', 0, 0), 'borderwidth': ('borderwidth', 'borderWidth', 'BorderWidth', <pixel object at 023253C0>, <pixel object at 023253C0>), 'pady': ('pady', 'padY', 'Pad', <pixel object at 023254F8>, <pixel object at 023254F8>), 'padx': ('padx', 'padX', 'Pad', <pixel object at 023253D8>, <pixel object at 023253D8>), 'font': ('font', 'font', 'Font', <font object at 0230DEB8>, 'TkDefaultFont'), 'activeforeground': ('activeforeground', 'activeForeground', 'Background', <color object at 02301EE8>, 'SystemButtonText'), 'activebackground': ('activebackground', 'activeBackground', 'Foreground', <border object at 02302398>, 'SystemButtonFace'), 'underline': ('underline', 'underline', 'Underline', -1, -1), 'width': ('width', 'width', 'Width', 0, 0), 'state': ('state', 'state', 'State', <index object at 02325378>, 'normal'), 'highlightcolor': ('highlightcolor', 'highlightColor', 'HighlightColor', <color object at 02325570>, 'SystemWindowFrame'), 'textvariable': ('textvariable', 'textVariable', 'Variable', '', ''), 'overrelief': ('overrelief', 'overRelief', 'OverRelief', '', ''), 'takefocus': ('takefocus', 'takeFocus', 'TakeFocus', '', ''), 'bd': ('bd', '-borderwidth'), 'foreground': ('foreground', 'foreground', 'Foreground', <color object at 03047630>, 'SystemButtonText'), 'bg': ('bg', '-background'), 'repeatinterval': ('repeatinterval', 'repeatInterval', 'RepeatInterval', 0, 0), 'repeatdelay': ('repeatdelay', 'repeatDelay', 'RepeatDelay', 0, 0), 'background': ('background', 'background', 'Background', <border object at 022BE118>, 'SystemButtonFace'), 'fg': ('fg', '-foreground'), 'bitmap': ('bitmap', 'bitmap', 'Bitmap', '', ''), 'highlightbackground': ('highlightbackground', 'highlightBackground', 'HighlightBackground', <border object at 02325390>, 'SystemButtonFace'), 'disabledforeground': ('disabledforeground', 'disabledForeground', 'DisabledForeground', <color object at 0230DA50>, 'SystemDisabledText'), 'wraplength': ('wraplength', 'wrapLength', 'WrapLength', <pixel object at 023252D0>, <pixel object at 023252D0>), 'default': ('default', 'default', 'Default', <index object at 0230DFF0>, 'disabled'), 'cursor': ('cursor', 'cursor', 'Cursor', '', ''), 'command': ('command', 'command', 'Command', '', ''), 'relief': ('relief', 'relief', 'Relief', <index object at 02325420>, 'raised'), 'anchor': ('anchor', 'anchor', 'Anchor', <index object at 02301D68>, 'center'), 'justify': ('justify', 'justify', 'Justify', <index object at 02325348>, 'center')}
备注: keys()方法中并没有包含name属性,因为name属性只能在Widget对象创建的时候指定。
因此通过btn[‘name’] = ‘ok’ 的形式指定‘name’属性。
5. 例子2:获取输入组件的值 (tkinter中的变量)
- http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/control-variables.html
跟输入相关的组件,Entry, spinbox, checkbutton, radiobutton, scale,listbox
- 对于,checkbutton, radiobutton, 和scale,可以通过
- 创建 StringVar,IntVar,DoubleVar, BooleanVar 类型的变量
var
- 通过
var
变量设置这些组件的variable 属性 - 通过
var.set(value)
和var.get()
设置和获取值
- 创建 StringVar,IntVar,DoubleVar, BooleanVar 类型的变量
- 对于entry和spinbox,(没有variable属性)
- Entry没有command属性,但是有validatecommand, xscrollcommand
- spinbox有command属性
- 两者都可以通过设置textvariable 属性来设置和获取当前的输入值
- var.set(value) var.get()
- 也可以直接通过组件的get方法获取值 (默认都是StringVar类型)
- wgt_entry.get(), wgt_spinbox.get()
- 对于listbox