美文网首页
tkinter 深度解析

tkinter 深度解析

作者: 水之心 | 来源:发表于2020-09-02 17:01 被阅读0次

为了方便:

import tkinter as tk

1 name 标识组件

tkinter 使用 name 选项标识了小部件,且只能在创建小部件时设置 name 选项:

root = tk.Tk()
t = tk.Toplevel(root, name='啊')
f = tk.Frame(t, name='child')

t, f

输出:

(<tkinter.Toplevel object .啊>, <tkinter.Frame object .啊.child>)

小部件是以 . 来标识组件之间的继承关系的:

root = tk.Tk()
t = tk.Toplevel(root)
f = tk.Frame(t)
f2 = tk.Frame(t)
b = tk.Button(f2)
for name in str(b).split('.'):
    print(name, name.isidentifier())

输出:

 False
!toplevel False
!frame2 False
!button False

小部件的继承关系可以看作是一颗树,使用 widget._w 可以获取其名称:

root = tk.Tk()
t = tk.Toplevel(root)
f = tk.Frame(t)
f2 = tk.Frame(t)
b = tk.Button(f2)

print(str(b) == b._w)
b._w, repr(b)

输出

True

('.!toplevel.!frame2.!button',
 '<tkinter.Button object .!toplevel.!frame2.!button>')

2 Misc

2.1 tk_setPalette 为所有小部件元素设置新的配色方案

单一颜色作为参数将导致 Tk 小部件元素的所有颜色都从该颜色派生。或者,可以给出几个关键字参数及其相关颜色。以下关键字有效:

activeBackground, foreground, selectColor,
activeForeground, highlightBackground, selectBackground,
background, highlightColor, selectForeground,
disabledForeground, insertBackground, troughColor.

root = tk.Tk()
root.tk_setPalette('white')
print(root['background']) # 打印背景 
root.tk_setPalette('black')
print(root['background']) # 打印背景
root.mainloop()

输出:

white
black

效果:

也可以这样:

root = tk.Tk()
root.tk_setPalette(background='blue', highlightColor='yellow')
print(root['background'], root['highlightcolor'])
root.mainloop()

输出:

blue yellow

效果:

2.2 update

进入事件循环,直到 Tcl 处理完所有未决(pending)事件。

def update_idletasks(self):
        """Enter event loop until all idle callbacks have been called. This
        will update the display of windows but not process events caused by
        the user."""
        self.tk.call('update', 'idletasks')

2.3 after

def after(self, ms, func=None, *args)ms 以毫秒为单位指定时间。func 提供应调用的功能。附加参数作为函数(func)调用的参数给出。返回标识符以使用 after_cancel 取消调度(scheduling)。

2.4 after_idle

after_idle(self, func, *args):如果 Tcl 主循环没有要处理的事件,则调用 func 一次。

2.5 after_cancel

after_cancel(self, id):取消以 id 标识的函数的计划(scheduling)。

2.6 clipboard

clipboard_get(self, **kw)(等价于 selection_get(CLIPBOARD))在窗口显示屏上从剪贴板中检索数据。window 关键字默认为 Tkinter 应用程序的根窗口。type 关键字指定返回数据的形式,并且应为原子名称,例如 STRING 或 FILE_NAME。除 X11 以外,类型默认为 STRING,X11 的默认值为尝试 UTF8_STRING 并回退至 STRING。

clipboard_clear(self, **kw) 清除 Tk 剪贴板中的数据。为可选的 displayof 关键字参数指定的小部件指定目标显示。

clipboard_append(self, string, **kw):将 STRING 附加到 Tk 剪贴板。在可选的 displayof 关键字参数中指定的小部件指定目标显示。可以使用 selection_get 检索剪贴板。

root.clipboard_clear()
root.clipboard_append('Ùñî')
print(root.clipboard_get())
root.clipboard_append('çōđě')
print(root.clipboard_get())
root.clipboard_clear()

输出:

Ùñî
Ùñîçōđě

相关文章

网友评论

      本文标题:tkinter 深度解析

      本文链接:https://www.haomeiwen.com/subject/dlkwsktx.html