Tkinter пытается уничтожить метку, определенную внутри функции после ее завершения - PullRequest
0 голосов
/ 17 мая 2018
from tkinter import *

def spaces(int1,int2):
    if int1 == 1:
        return(int2*"\n")
    else:
        return(int2*" ")
def submitButton():
    subButton_text = subButton.get()
    try:
        informationText.destroy()
    except UnboundLocalError:
        print("an error has occured.")
        print("Attempting to run with the error.")
        pass
    informationText = Label(window, text=subButton_text, bg = "grey",
      fg = "white", font = "none 12 bold")
    informationText.grid(row=4,column=0,sticky=W)
    #informationText.destroy()
    #return informationText
def exit_Button():
    window.destroy()

window = Tk()
window.title("Learning tkinter")
window.configure(background="grey")
subButton = StringVar()



#pic1 = PhotoImage(file="test.png")
#Label(window, image=pic1, bg = "grey").grid(row = 0, column = 0, sticky=W)

Label(window, text="Please enter a value", bg = "grey",
      fg = "white", font = "none 12 bold").grid(row=0,column=0,sticky=W)

Entry(window, width=50, bg="white",textvariable=subButton).grid(row=1,column=0,stick=W)
subButton.set("default value")

Button(window, text="Submit", width=10,
       command = submitButton).grid(row=2,column=0, sticky=W)

Label (window, text="\nInformation:", bg="grey", fg="white",
       font="none 12 bold").grid(row=3,column=0, sticky=W)

Button (window, text="Save\nand exit", width=8,
        command=exit_Button).grid(row=0,column=2,sticky=NW)

Label(window, text=spaces(1,10), bg = "grey",
      fg = "white", font = "none 12 bold").grid(row=100,column=0,sticky=W)
Label(window, text=spaces(2,20), bg = "grey",
      fg = "white", font = "none 12 bold").grid(row=0,column=1,sticky=W)
window.mainloop()

Это мой код для простой программы tkinter. Когда «submitButton» создает, создайте метку с именем «informationText». Но когда кнопка нажимается снова с новым текстом, я хочу, чтобы он уничтожил старый текст, но он не работает. Если я уничтожаю текст сразу после его создания (закомментированный), он работает.

Это потому, что я объявил это в функции? Если так, как я могу уничтожить его после завершения функции?

(сначала спросите, советы будут полезны для улучшения вопросов в будущем)

1 Ответ

0 голосов
/ 17 мая 2018

Если вы напишите свой код в классе, вы сможете использовать атрибуты класса, чтобы сохранить свою метку и обновить ее позже.

Если исходить из того, что вы пытаетесь сделать с помощью приведенного ниже кода, это будет классэквивалент, который работает.Тем не менее, я думаю, что вы должны обновить метку, а не уничтожать ее.

import tkinter as tk


class MyApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        self.information_text = None
        self.title("Learning tkinter")
        self.configure(background="grey")
        self.subButton = tk.StringVar()

        tk.Label(self, text="Please enter a value", bg = "grey", fg = "white", font = "none 12 bold").grid(row=0,column=0,sticky="w")
        tk.Entry(self, width=50, bg="white",textvariable=self.subButton).grid(row=1,column=0,stick="w")

        self.subButton.set("default value")

        tk.Button(self, text="Submit", width=10, command = self.submitButton).grid(row=2,column=0, sticky="w")
        tk.Label (self, text="\nInformation:", bg="grey", fg="white", font="none 12 bold").grid(row=3,column=0, sticky="w")
        tk.Button (self, text="Save\nand exit", width=8, command=self.exit_Button).grid(row=0,column=2,sticky="nw")
        tk.Label(self, text=self.spaces(1,10), bg = "grey", fg = "white", font = "none 12 bold").grid(row=100,column=0,sticky="w")
        tk.Label(self, text=self.spaces(2,20), bg = "grey", fg = "white", font = "none 12 bold").grid(row=0,column=1,sticky="w")

    def spaces(self, int1, int2):
        if int1 == 1:
            return(int2*"\n")
        else:
            return(int2*" ")
    def submitButton(self):

        try:
            self.information_text.destroy()
            self.information_text = None
        except:
            print("an error has occured.")
            print("Attempting to run with the error.")

        self.information_text = tk.Label(self, text=self.subButton.get(), bg = "grey", fg = "white", font = "none 12 bold")
        self.information_text.grid(row=4,column=0,sticky="w")

    def exit_Button(self):
        self.destroy()


if __name__ == "__main__":
    app = MyApp()
    app.mainloop()

В моем втором примере будет использоваться config() для обновления метки вместо того, чтобы уничтожать ее.Я думаю, что это может работать лучше для ваших нужд здесь.

import tkinter as tk


class MyApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)


        self.title("Learning tkinter")
        self.configure(background="grey")
        self.subButton = tk.StringVar()

        tk.Label(self, text="Please enter a value", bg = "grey", fg = "white", font = "none 12 bold").grid(row=0,column=0,sticky="w")
        tk.Entry(self, width=50, bg="white",textvariable=self.subButton).grid(row=1,column=0,stick="w")

        self.subButton.set("default value")

        tk.Button(self, text="Submit", width=10, command = self.submitButton).grid(row=2,column=0, sticky="w")
        tk.Label (self, text="\nInformation:", bg="grey", fg="white", font="none 12 bold").grid(row=3,column=0, sticky="w")
        tk.Button (self, text="Save\nand exit", width=8, command=self.exit_Button).grid(row=0,column=2,sticky="nw")
        tk.Label(self, text=self.spaces(1,10), bg = "grey", fg = "white", font = "none 12 bold").grid(row=100,column=0,sticky="w")
        tk.Label(self, text=self.spaces(2,20), bg = "grey", fg = "white", font = "none 12 bold").grid(row=0,column=1,sticky="w")

        self.information_text = tk.Label(self, text="", bg = "grey", fg = "white", font = "none 12 bold")
        self.information_text.grid(row=4,column=0,sticky="w")

    def spaces(self, int1, int2):
        if int1 == 1:
            return(int2*"\n")
        else:
            return(int2*" ")
    def submitButton(self):
        self.information_text.config(text=self.subButton.get())

    def exit_Button(self):
        self.destroy()


if __name__ == "__main__":
    app = MyApp()
    app.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...