【问题标题】:Unexpected results with delete method使用删除方法的意外结果
【发布时间】:2012-02-22 09:16:36
【问题描述】:

在一本学习 Python 3 编程的书中找到了这个练习……我必须创建一个从 Frame 派生的新 App 类。它必须显示一张脸和 2 个按钮,一个用来画张开的嘴,另一个用来画一条线(张开和合上嘴 - 新手练习)。

下面是我所做的,它几乎可以正常工作:打开按钮工作正常,如果有一条线(闭嘴),它会删除它,但闭嘴按钮会画线而不删除张嘴,尽管在我看来我使用完全相同的删除方法来处理... 我的问题:为什么它适用于一个按钮而不是另一个?你得到同样的结果吗?

class Application(Frame):
    "main canvas and buttons"

    def __init__(self, boss =None):
        Frame.__init__(self)
        self.can = Canvas(self, width=400, height =400, bg ='ivory')
        self.can.pack(side =TOP, padx =5, pady =5)
        self.face=Visage(self.can, 50, 50)
        self.bouche=2
        Button(self, text ="Ouvrir", command =self.ouvrirBouche).pack(side =LEFT)
        Button(self, text ="Fermer", command =self.fermerBouche).pack(side =LEFT)

    def ouvrirBouche(self):
        "draws the open mouth and delete the closed one if any"
        if (self.bouche != 0):
            self.ouvre=cercle(self.can, 200, 260, 35)
            if (self.bouche ==1):
                print(self.bouche)
                self.can.delete(self.ferme)
            self.bouche=0

    def fermerBouche(self):
        "draws the closed mouth and delete the open one if any"
        if (self.bouche != 1):
            self.ferme= self.can.create_line(170, 260, 230, 260)
            if (self.bouche ==0):
                print(self.bouche)
                self.can.delete(self.ouvre)
            self.bouche=1


class Visage(object):
    "drawing a face in canvas canv"
    def __init__(self, canv, x, y):
        self.canv, self.x, self.y = canv, x, y
        cercle(canv, x+150, y+150, 130)
        cercle(canv, x+100, y+100, 20)
        cercle(canv, x+200, y+100, 20)


if __name__ == '__main__':
    root=Tk()
    app=Application(root)
    app.pack(side=TOP)
    root.mainloop()

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    您可能定义了一个函数cercle 来绘制法国圆圈。
    该函数应如下所示:

    def cercle(canv, x, y, rad):
        return canv.create_oval(x-rad, y-rad, x+rad, y+rad, width=2)
    

    请注意,该函数必须返回圆形对象。否则 self.ouvre 为 None 然后你不能删除它,因为你没有对 self.can.delete(self.ouvre) 中的对象的引用。

    在 windows 7 64bit 中使用 python 3.2 测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-24
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多