2013-10-04 117 views
0

我正在從一本書開始工作,並且有一個練習,用戶從單選按鈕中選擇一個圖形,並通過選擇一個複選按鈕來指定它是否被填充。在最初看起來像一個簡單的練習的日子裏奮鬥了幾天,我完全疲憊不堪。如何使用名爲「填充」的複選框來更改矩形和橢圓形的填充? 任何幫助表示讚賞。tkinter複選框選擇影響形狀

from tkinter import * 

class SelectShapes: 
    def __init__(self): 
     window = Tk() 
     window.title("Select Shapes") 

     self.canvas = Canvas(window, width = 500, height = 400, bg = "white") 
     self.canvas.pack() 

     frame1 = Frame(window) 
     frame1.pack() 

     self.v1 = IntVar() 
     btRectangle = Radiobutton(frame1, text = "Rectangle", variable = self.v1, value = 1, command = self.processRadiobutton) 
     btOval = Radiobutton(frame1, text = "Oval", variable = self.v1, value = 2, command = self.processRadiobutton) 
     btRectangle.grid(row = 2, column = 1) 
     btOval.grid(row = 2, column = 2) 

     self.v2 = IntVar() 
     cbtFill = Checkbutton(frame1, text = "Fill", variable = self.v2, command = self.processCheckbutton) 
     cbtFill.grid(row = 2, column = 3) 


     window.mainloop() 

    def processCheckbutton(self): 
     if self.v2.get() == 1: 
      self.v1["fill"] = "red" 
     else: 
      return False 

    def processRadiobutton(self): 
     if self.v1.get() == 1: 
      self.canvas.delete("rect", "oval") 
      self.canvas.create_rectangle(10, 10, 250, 200, tags = "rect") 
      self.canvas.update() 
     elif self.v1.get() == 2: 
      self.canvas.delete("rect", "oval") 
      self.canvas.create_oval(10, 10, 250, 200, tags = "oval") 
      self.canvas.update() 


SelectShapes() # Create GUI 
+0

您的代碼示例格式不正確。 –

+0

我重新粘貼它,使其看起來更好。這是你的意思嗎? – ohvonbraun

+0

是的,它看起來好多了。 –

回答

0

問題在於你的processCheckbutton函數。它看起來像是以某種方式將self.v1作爲畫布對象,但它不是 - 它只是IntVar存儲Checkbutton的狀態。你需要在那裏添加一行改變畫布對象的fill屬性。要做到這一點,首先需要保存當前畫布對象的ID:

processRadioButton功能:

 self.shapeID = self.canvas.create_rectangle(10, 10, 250, 200, tags = "rect") 
#  ^^^^^^^^^^^^ save the ID of the object you create 

 self.shapeID = self.canvas.create_oval(10, 10, 250, 200, tags = "oval") 
#  ^^^^^^^^^^^^ save the ID of the object you create 

終於在processCheckbutton功能:

def processCheckbutton(self): 
    if self.shapeID is not None: 
     if self.v2.get() == 1: 
      self.canvas.itemconfig(self.shapeID, fill="red") 
#         ^^^^^^^^^^^^ use the saved ID to access and modify the canvas object. 
     else: 
      self.canvas.itemconfig(self.shapeID, fill="") 
#              ^^ Change the fill back to transparent if you uncheck the checkbox 
+0

太好了。你的解釋和例子對我的小腦袋來說是完美的。我完全理解發生了什麼。非常感謝! – ohvonbraun

+0

很高興提供幫助 - 如果這解決了您的問題,請考慮將其標記爲「已接受」,以便未來的讀者很容易就可以告訴問題已解決。 – Brionius