2013-10-04 80 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