如何使用窗口小部件选项值作为条件来创建if语句?

时间:2016-03-05 12:15:32

标签: python if-statement tkinter conditional-statements

我们说我有一个按钮:

tl.config(bd=0 ,image=photo1 ,width="100",height="100",command=lambda: functionPlus(tl))  

功能是:

def functionPlus(button):

   global turn

   if (turn==1 or turn==3 or turn==5 or turn==7 or turn==9):
       button.config(image=photo2,width="100",height="100")
       turn +=1

   elif (turn==2 or turn==4 or turn==6 or turn==8) :
       button.config(image=photo3,width="100",height="100")
       turn+=1

我想添加一个' if'在函数中,这将具有按钮图像的条件。例如:

if button.config(image=photo2 == True) :
   anotherFunction()

提前致谢。

2 个答案:

答案 0 :(得分:5)

首先,从不使用表达式模式something=something else == True

其次,看看this related (but not duplicate) question

正如您所看到的,cget方法将返回选项的当前值。作为this manual page mentionscget类似于widget["option"]

所以,直接回答您的问题,您需要的if条件如下:

if button['image']==photo2:
   anotherFunction()

答案 1 :(得分:0)

我是新来的,无法发表评论。我希望我不是通过诉诸回答来炫耀SO政策。

@Tersosauros

  

"首先,永远不要使用表达式pattern something = something else ==   !真"

你在哪里看到这种模式,为什么要避免这种模式?什么可以取代它? (我知道你是一个tersosaurus而且"从不使用X"只是看起来很简洁而且没有信息)。

@Arwan Credoz我知道你得到了答案但是......如果你只想检查"转向"是一个偶数/奇数并且在给定范围内,使用边界检查后跟模数(也许这是@Tersosauros暗示的?)。 此外,"转"的价值如果它在范围(0,10)内,则总是会增加,所以不需要写'&34;转+ = 1"两次。如果我能正确理解你的意图,你可能会重写" functionPlus"这样的事情并添加Tersosaurus'酌情补充:

def functionPlus(button):
    global turn
    if 0 < turn < 10:
        if turn % 2 == 0:
            button.config(image=photo3,width="100",height="100")
        else:
            button.config(image=photo2,width="100",height="100")
        turn += 1