2017-02-23 61 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