Python (TKinter) GUI не будет отображать текст - PullRequest
0 голосов
/ 13 мая 2018

код:

from tkinter import*

root = Tk()
root.title("Mood Control")
root.geometry("500x500")

label1 = Label(root, text="From 1-5 how would you rate your mood today? ", font=("arial",15, "bold"), fg="black").place(x=10, y=40)


def sad():
    photo = PhotoImage(file="happyturtle.gif")
    label = Label(image=photo).place(x=135, y=200)
    label.image = photo
    label.pack()

def happy():
    photo = PhotoImage(file="sadcat.gif")
    label = Label(image=photo).place(x=100, y=250)
    label.image = photo
    label.pack()
    label2 = labe



button1 = Button(root, text="1", width=3, height=3, bg="lightgrey", command=sad).place(x=20, y=100)
button2 = Button(root, text="2", width=3, height=3, bg="white", command=sad).place(x=60, y=100)
button3 = Button(root, text="3", width=3, height=3, bg="lightgrey", command=happy).place(x=100, y=100)
button4 = Button(root, text="4", width=3, height=3, bg="white", command=happy).place(x=140, y=100)
button5 = Button(root, text="5", width=3, height=3, bg="lightgrey", command=happy).place(x=180, y=100)

root.mainloop()

По сути, я пытаюсь сделать забавное маленькое приложение, которое контролирует ваше настроение, вы никогда не будете слишком счастливы или грустны. Поэтому, если бы я нажал 1 или 2, на экране была бы картинка счастливой черепахи, чтобы подбодрить вас. если бы я нажал 3-5, это показало бы изображение грустного кота, чтобы убедиться, что ты не слишком счастлив. Я все выяснил, но у меня есть одна проблема, я хотел бы, чтобы текст над изображениями отображался, например: «Вы слишком счастлив, вот фигура грустного кота ". Но когда я пытаюсь сделать это, он никогда не отображает текст. Я пытался сделать это так:

def happy ():

photo = PhotoImage(file="sadcat.gif")
label = Label(image=photo).place(x=100, y=250)
label.image = photo
label.pack()
label2 = Label(root, text="You are too happy, here's a picture of a sad cat", font=("arial",10, "bold"), fg="black").place(x=100, y=40)
# above line is what is supposed to display the text, it doesnt.

Также при наведении указателя мыши на «label2» написано, что «локальная переменная« label2 »не используется». Как мне это исправить?

Любые ответы оценены

1 Ответ

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

Есть несколько проблем с функцией happy.

def happy():
    photo = PhotoImage(file="sadcat.gif")
    label = Label(image=photo).place(x=100, y=250)
    label.image = photo
    label.pack()
    label2 = Label(root, text="You are too happy, here's a picture of a sad cat", font=("arial",10, "bold"), fg="black").place(x=100, y=40)
    # above line is what is supposed to display the text, it doesnt.

Строка label = Label(image=photo).place(x=100, y=250) устанавливает переменную label для возврата из place ().Объект, возвращаемый методом place, не будет иметь атрибута изображения, поэтому строка label.image = photo вызовет ошибку.Если вы хотите ссылку на метку, попробуйте:

photo = PhotoImage(file="sadcat.gif")
label = Label(image=photo)

label.place(x=100, y=250)

Сейчас label.image = photo не приведет к ошибке, но эту строку можно убрать, когда вы устанавливаете изображение при Label(image=photo).label.pack() следует удалить, поскольку вы уже используете менеджер геометрии места.

Выход:

def happy():
    photo = PhotoImage(file="sadcat.gif")
    label = Label(image=photo).place(x=100, y=250)
    label2 = Label(root, text="You are too happy, here's a picture of a sad cat", font=("arial",10, "bold"), fg="black").place(x=100, y=40)
    # above line is what is supposed to display the text, it doesnt.

Редактировать:

from tkinter import*

root = Tk()
root.title("Mood Control")
root.geometry("500x500")

label1 = Label(root, text="From 1-5 how would you rate your mood today? ", font=("arial",15, "bold"), fg="black")
label1.place(x=10, y=40)


def sad():
    photo = PhotoImage(file="tenor1.gif")
    label = Label(root, image=photo)
    label.place(x=100, y=250)
    label.image = photo


def happy():
    label1['text'] = "You are too happy, here's a picture of a sad cat"
    photo = PhotoImage(file="tenor.gif")
    label = Label(root, image=photo)
    label.place(x=100, y=250)
    label.image = photo
    # above line is what is supposed to display the text, it doesnt.




button1 = Button(root, text="1", width=3, height=3, bg="lightgrey", command=sad).place(x=20, y=100)
button2 = Button(root, text="2", width=3, height=3, bg="white", command=sad).place(x=60, y=100)
button3 = Button(root, text="3", width=3, height=3, bg="lightgrey", command=happy).place(x=100, y=100)
button4 = Button(root, text="4", width=3, height=3, bg="white", command=happy).place(x=140, y=100)
button5 = Button(root, text="5", width=3, height=3, bg="lightgrey", command=happy).place(x=180, y=100)

root.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...