Tkinter按钮与命令是否

时间:2019-01-07 18:39:05

标签: python button tkinter

我确定这对您来说是一个非常简单的问题,但对我来说却是一个巨大的问题。

我不知道如何使用if和else为tkinter按钮创建命令。 实际上,想法是,当我按下按钮后在条目上输入单词“ white”时,必须向我显示带有“ RIGHT”的标签,但是使用此代码,按钮总是向我显示错误...为什么?

这是代码:

# 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()

1 个答案:

答案 0 :(得分:0)

在您的代码中,ment是一个tk StringVar()对象。为了读取变量的值,您需要使用.get()方法:

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

如果您打印出ment,您会注意到它上面写着PY_VAR0或类似名称(这是字符串变量对象的Tcl名称),因此它永远不会等于'white'