当创建另一个相同类型的对象时,如何复制一个tkinter对象的选项?

2024-09-23 22:32:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用另一个矩形的选项在Tkinter中画一个矩形。我不能硬编码选项/从第一个矩形得到哪些选项,因为我事先不知道它将有哪些选项。在

我使用options = canvas.itemconfig(first)获取第一个矩形选项的字典,然后使用 second = canvas.create_rectangle(150, 50, 300, 150, **options)但出现以下错误:

_tkinter.TclError: bitmap "stipple {} {} {} {}" not defined

然后,我过滤了options字典以删除没有值的参数(例如stipple),但是得到了以下错误消息:

_tkinter.TclError: unknown color name "black red"

因为outline有两个值("black"和{}),尽管我在绘制第一个矩形时只给了一个值

我还给了第一个矩形两个标记,'rect'和{},这两个标记已经改为'rect orig'

下面是选项字典在过滤没有值的参数之前和之后的样子:

原词典:

{'stipple': ('stipple', '', '', '', ''), 'disabledoutlinestipple': ('disabledoutlinestipple', '', '', '', ''), 'offset': ('offset', '', '', '0,0', '0,0'), 'dash': ('dash', '', '', '', ''), 'disabledwidth': ('disabledwidth', '', '', '0.0', '0'), 'activeoutlinestipple': ('activeoutlinestipple', '', '', '', ''), 'dashoffset': ('dashoffset', '', '', '0', '0'), 'activewidth': ('activewidth', '', '', '0.0', '0.0'), 'fill': ('fill', '', '', '', 'blue'), 'disabledoutline': ('disabledoutline', '', '', '', ''), 'disabledfill': ('disabledfill', '', '', '', ''), 'disableddash': ('disableddash', '', '', '', ''), 'width': ('width', '', '', '1.0', '1.0'), 'state': ('state', '', '', '', ''), 'outlinestipple': ('outlinestipple', '', '', '', ''), 'disabledstipple': ('disabledstipple', '', '', '', ''), 'activedash': ('activedash', '', '', '', ''), 'tags': ('tags', '', '', '', 'rect orig'), 'activestipple': ('activestipple', '', '', '', ''), 'activeoutline': ('activeoutline', '', '', '', ''), 'outlineoffset': ('outlineoffset', '', '', '0,0', '0,0'), 'activefill': ('activefill', '', '', '', ''), 'outline': ('outline', '', '', 'black', 'red')}

筛选词典:

{'outline': ('black', 'red'), 'width': ('1.0', '1.0'), 'offset': ('0,0', '0,0'), 'disabledwidth': ('0.0', '0'), 'outlineoffset': ('0,0', '0,0'), 'dashoffset': ('0', '0'), 'activewidth': ('0.0', '0.0'), 'tags': ('rect orig',), 'fill': ('blue',)}

这是原始代码:

from Tkinter import *

root = Tk()
canvas = Canvas(root, width=600, height=400)
canvas.pack()

first = canvas.create_rectangle(50, 50, 200, 150, outline="red",
                                fill="blue", tags=("rect", "org"))

options = canvas.itemconfig(first)
print options

#second = canvas.create_rectangle(150, 50, 300, 150, **options)

root.mainloop()

Tags: rect字典选项createtagsredwidthfill
1条回答
网友
1楼 · 发布于 2024-09-23 22:32:14

如您所见,itemconfig不返回简单键/值对的字典。对于每个选项,它将返回由以下五项组成的元组:

  1. 选项名称
  2. 选项数据库的选项名称
  3. 选项数据库的选项类
  4. 默认值
  5. 当前值

如果要复制所有选项,则需要为每个选项返回最后一项。在

你可以很容易地理解字典:

config = canvas.itemconfig(canvas_tag_or_id)
new_config = {key: config[key][-1] for key in config.keys()}
canvas.create_rectangle(coords, **new_config)

有关详细信息,请参阅

相关问题 更多 >