【问题标题】:Update image of a button depending on its previous image根据之前的图像更新按钮的图像
【发布时间】:2017-01-09 05:01:12
【问题描述】:

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

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')," 不工作)。

你对这个问题有什么想法吗?

谢谢。

【问题讨论】:

  • 尝试将其与您的 start_image 进行比较,而不是字符串 'start_image'

标签: python image tkinter


【解决方案1】:

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)

这确实有效,我已经对其进行了测试,希望对您有所帮助! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    相关资源
    最近更新 更多