【问题标题】:Python tkinter destroying a labelPython tkinter 破坏标签
【发布时间】:2018-09-26 17:34:43
【问题描述】:

我知道有很多资料显示了如何使用 destroy 命令,但由于某种原因,这忽略了 destroy 命令并继续创建更多文本标签。关于为什么会这样的任何想法?代码是我正在制作的一个小游戏。

你可以在“integrity()”下找到我要销毁的标签

    from tkinter import *
from random import randrange
class Window(Frame):
    def position(self):
        return {"x":randrange(0,350),"y":randrange(0,250)}
    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.master = master
        self.__init__window()
    def __init__window(self):
        global count
        count=0
        self.master.title("GUI")
        self.pack(fill=BOTH, expand=1)
        self.Button1 = Button(self, text="Click me",command=self.Message)
        self.Button1.place(**self.position())
        self.Button2 = Button(self, text="Click me if you can",command=self.integrity)
        self.Button2.place(**self.position())
        menu=Menu(self.master)
        self.master.config(menu=menu)
        file = Menu(menu)
        file.add_command(label="Exit", command=self.client_exit)
        menu.add_cascade(label="File",menu=file)
        edit = Menu(menu)
        edit.add_command(label="Starto", command=self.showText)
        menu.add_cascade(label="Edit", menu=edit)
    def Message(self):
        print("Hello world")
        self.Button1.place(**self.position())
    def showText(self):
        text = Label(self, text="Clicks: ")
        text.pack()
    def integrity(self):
        self.Button2.place(**self.position())
        global count
        count=count+1
        self.text1 = Label(self, text=count)
        self.text1.destroy()
        self.text1 = Label(self,text=count)
        self.text1.pack()
        print("Clicks: ",count)
        if count<5:
            print("(づòДó)づ")
            print("Dont click!")
            print("﴾´• ω •`﴿\n")
        elif count<10:
            print("ヽ(òДó)ノ")
            print("Stop it")
            print("(づòДó)づ\n")
        elif count<15:
            print("﴾⇀∀↼﴿")
            print("Stop it please!\n")
        else:
            print("Fine you win just stop! ლ(>Д<ლ)\n")
        def client_exit(self):
        exit()
root = Tk()
root.geometry("400x300")
app = Window(root)
root.mainloop()

【问题讨论】:

  • 您创建一个标签,然后立即销毁它并重新创建它。为什么你认为它忽略了 destroy 命令?
  • 我试图让它替换标签,这样它就不会继续堆叠标签

标签: python-3.x tkinter destroy


【解决方案1】:

问题出在这三行代码:

self.text1 = Label(self, text=count)
self.text1.destroy()
self.text1 = Label(self,text=count)

您正在创建一个标签,立即销毁它,然后再次创建它。所以,在这段代码的末尾你有一个标签。

下次调用代码时,您已经有了一个标签。然后你创建另一个标签(so, two),然后立即销毁它(so, one),然后立即创建另一个(so, two)。

下次调用代码时,您已经有了两个标签。然后你创建另一个标签(so,3),然后立即销毁它(so,2),然后立即创建另一个(so,3)

...等等。

解决的办法是去掉那三行代码,在__init__window里面创建self.text1,然后每次调用函数的时候只改变标签上的文字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-30
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多