2017-02-23 63 views
0

我想在Tkinter中使用另一个矩形的选项绘制一个矩形。我不能硬编码选项/从第一个矩形获得哪些选项,因为我事先不知道它将具有哪些选项。如何在创建相同类型的另一个对象时复制一个tkinter对象的选项?

我以前options = canvas.itemconfig(first)获得的第一个矩形的选择字典,然后画了使用 second = canvas.create_rectangle(150, 50, 300, 150, **options)第二个矩形,但得到了以下错误:

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

我,然后过滤选项字典中删除参数没有值(例如stipple),但随后得到了下面的错误消息:

_tkinter.TclError: unknown color name "black red"

因为outline有两个值("black""red"),虽然我给它只有一个值而绘制一个矩形

我也给了第一个矩形的两个标签,'rect''orig',这已被更改为'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() 
+0

什么'outile'? – martineau

+0

错字,我的意思是“大纲”。 – Khristos

回答

1

正如你所看到的,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) 

欲了解更多信息,请参阅https://docs.python.org/2/library/tkinter.html#setting-options

+0

工作,谢谢。 – Khristos