【问题标题】:How to delete in a class an object created from another class如何在一个类中删除从另一个类创建的对象
【发布时间】:2019-07-13 09:22:19
【问题描述】:

我正在学习python和tkinter,我尝试从B类中的A类中删除一个对象,但是没有任何反应,当我点击butB时也没有错误消息。感谢您的帮助

from tkinter import *
class FaceDom(object):
    def __init__(self, can):
        self.can =can
        self.can.create_line(10, 10, 90, 90, fill ='red',width=5)   
class Projet(Frame):
    def __init__(self, larg, haut):
        Frame.__init__(self)
        self.larg, self.haut = larg, haut
        self.can = Canvas(self, bg='dark green', width =larg, height =haut)
        self.can.pack()
        bList = [("ligne", self.butA),("Delete",self.butB)]
        for b in bList:
            Button(self, text =b[0], command =b[1]).pack()
        self.pack()
    def butA(self):     
        self.x=FaceDom(self.can)
        print(self.x)
    def butB(self):
        self.can.delete(FaceDom.x)      
Projet(100, 100).mainloop()

【问题讨论】:

  • create_line 给出你必须使用的 ID 从画布中删除行。
  • 如果有,您希望删除对屏幕产生什么影响?
  • 当我运行它并按下按钮删除然后我看到错误。你有没有在控制台/终端/cmd.exe 中运行它来查看错误?

标签: python class tkinter


【解决方案1】:

create_line 提供您必须保留的 ID

self.id = self.can.create_line(10, 10, 90, 90, fill='red', width=5)

并使用它从画布中删除线条。

def butB(self):
    self.can.delete(self.x.id)      

您也可以使用此 ID 来移动线条或更改其配置(颜色等)


from tkinter import *

class FaceDom(object):
    def __init__(self, can):
        self.can = can
        self.id = self.can.create_line(10, 10, 90, 90, fill='red', width=5)

class Projet(Frame):

    def __init__(self, larg, haut):
        Frame.__init__(self)
        self.larg, self.haut = larg, haut
        self.can = Canvas(self, bg='dark green', width =larg, height =haut)
        self.can.pack()
        bList = [("ligne", self.butA),("Delete",self.butB)]
        for b in bList:
            Button(self, text =b[0], command =b[1]).pack()
        self.pack()

    def butA(self):     
        self.x = FaceDom(self.can)
        print(self.x)

    def butB(self):
        self.can.delete(self.x.id)      

Projet(100, 100).mainloop()

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
相关资源
最近更新 更多