影响形状的tkinter复选框选择

时间:2013-10-04 00:27:44

标签: checkbox 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 

1 个答案:

答案 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