【问题标题】:How to make an if statement using widget option values as conditions?如何使用小部件选项值作为条件制作 if 语句?
【发布时间】:2016-06-19 05:55:26
【问题描述】:

假设我有一个这个按钮:

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

提前致谢。

【问题讨论】:

    标签: python if-statement tkinter conditional-statements


    【解决方案1】:

    首先,永远不要使用表达式模式something=something else == True

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

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


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

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

    【讨论】:

    • 好的!感谢您的解决方案和建议,代码现在正在运行。
    【解决方案2】:

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

    @Tersosauros

    “首先,永远不要使用表达式模式something=something else == 真的!”

    您在哪里看到这种模式,为什么要避免这种模式?什么可以代替它? (我知道你是一只特龙,但“从不使用 X”似乎过于简洁且缺乏信息)。

    @Arwan Credoz 我知道您得到了答案,但是...如果您只是想检查“转”的值是否是偶数/奇数并且在给定范围内,请使用边界检查,然后使用模数相反(也许这是@Tersosauros 暗示的?)。 此外,如果 "turn" 的值在 range(0,10) 内,则它的值将始终递增,因此无需写两次 "turn+=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
    

    【讨论】:

    • 哈,有趣!我什至没有阅读太多该功能......但你是绝对正确的!那些 if 条件 in functionPlus 可以只使用模数。我的重点是下一个 if 语句(在单独的代码块中),它不起作用 - 所以我修复了它。
    • 关于a=b == True 模式的问题,最好在单独问题中提出(您自己的问题,这样您就可以获得一些声誉以通过该评论块),但本质上这与confusion of the equality and assignment operators有关。
    • @Tersosauros 是的,你回答了实际问题——我只是重构了一下(因此,我猜我的回答应该是评论)。无论如何,我忽略了最后一行(image=photo2 == True),所以我不明白你为什么首先提到滥用赋值/相等运算符。我的错。
    猜你喜欢
    • 2016-09-07
    • 1970-01-01
    • 2020-11-06
    • 2020-10-04
    • 2021-12-29
    • 2021-07-30
    • 2017-07-02
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多