简体   繁体   中英

Tkinter button with the command if or else

I'm sure that It's a very easy problem for you but huge for me.

I don't know how to create a command for my tkinter button with if and else. In fact the idea is that when I input on the entry the word 'white' after pressing the button it must show me the label with 'RIGHT' but with this code the button always shows me WRONG...why?

This is the Code:

# coding=utf-8
from tkinter import *
from tkinter import font
from PIL import ImageTk,Image
import time
from PIL import ImageTk,Image

schermata = Tk()
ment = StringVar()

schermata.geometry('750x500')
schermata.title('DANTE')

def comando():
    global input
    if ment=='white':
        time.sleep(1)
        risposta_giusta.pack()
        risposta_giusta.place(x=20, y=290)
    else:
        time.sleep(1)
        risposta_sbagliata.pack()
        risposta_sbagliata.place(x=20,y=290)

def resize_image(event):
    new_width = event.width
    new_height = event.height
    image = copy_of_image.resize((new_width, new_height))
    photo = ImageTk.PhotoImage(image)
    label.config(image = photo)
    label.image = photo #avoid garbage collection

image = Image.open('dante.gif')
copy_of_image = image.copy()
photo = ImageTk.PhotoImage(image)
label = Label(schermata, image = photo)
label.bind('<Configure>', resize_image)
label.pack(fill=BOTH, expand = YES)

font = ('Ubuntu',22)
font_2 = ('Ubuntu',12)
labelfont = ('Noto Serif CJK SC', 35, 'bold')
titolo = Label(schermata,text='DANTE',bg='#E5E3C6',fg='#BF000D')
titolo.config(font=labelfont)
titolo.pack(fill=BOTH, expand = YES)
titolo.place(x=20, y=20)

risposta_giusta = Label(schermata, text='RIGHT!!', font=font, bg='#E5E3C6',fg='#0F0000')
risposta_sbagliata = Label(schermata, text='WRONG', font=font, bg='#E5E3C6',fg='#0F0000')

domanda = Label(schermata, text="what is the color of Napoleone's horse?", font=font_2, bg='#E5E3C6',fg='red')
domanda.pack()
domanda.place(x=20, y=120)

input = Entry(schermata,textvariable=ment,bg='white',width=23,disabledbackground='black')
input.pack(ipady=3)
input.place(x=20, y=190)

bottone = Button(schermata,text='PARLA CON DANTE',command=comando,bg='#BF000D',fg='white')
bottone.pack()
bottone.place(x=20, y=245)

schermata.mainloop()

In your code, ment is a tk StringVar() object. In order to read the value of the variable you need to use the .get() method:

def comando():
    global input
    if ment.get()=='white':
        time.sleep(1)
        risposta_giusta.pack()
        risposta_giusta.place(x=20, y=290)

If you printed out ment You would notice it says PY_VAR0 or similar (which is Tcl name of the string variable object), so it will never equal to 'white' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM