根据以前的图像更新按钮的图像

时间:2016-09-01 10:40:00

标签: python image tkinter

我正在尝试在Tkinter(Pyhton)中编写一个开始/暂停按钮,但以下代码不起作用:

def startpause():
 if startpause_button.cget('image')=='start_image':
  startpause_button.config(image=pause_image)
 else:
  startpause_button.config(image=start_image)
return

start_image=ImageTk.PhotoImage(file='start.png')
pause_image=ImageTk.PhotoImage(file='pause.png')

startpause_button=ttk.Button(frame,image=start_image,command = startpause)

我理解问题是关于cget(返回('pyimage3'),)以及它返回的内容但是我不知道要把什么作为值来检查(“('pyimage3'),”不工作)。

你对这个问题有任何想法吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

startpause_button.cget('image')'start_image'是两个不同的东西,.cget('image')返回列表中图片的名称,例如('pyimage1',)。这意味着要比较它们,您需要使用[0]将其从列表中删除,并确保两个变量都是str()的字符串,因为'pyimage1'pyimage1也是两个不同的东西

import tkinter.ttk
from tkinter import Tk, PhotoImage

def startpause():
    global start_image
    if str(startpause_button.cget('image')[0])==str(start_image):
        startpause_button.config(image=pause_image)
    else:
        startpause_button.config(image=start_image)
    #return # i dont think you need this

global start_image
start_image=PhotoImage(file='start.gif')
pause_image=PhotoImage(file='pause.gif')

startpause_button=tkinter.ttk.Button(frame,image=start_image,command = startpause)

这确实有效,我已经测试过了,希望这可以帮到你! :)