【问题标题】:How can I update the photo within a button using radio buttons?如何使用单选按钮更新按钮内的照片?
【发布时间】:2016-10-28 21:08:42
【问题描述】:

我目前正在尝试学习如何使用 tkinter 构建 GUI,但我的测试应用程序遇到了问题。

我有一个在其上显示图像而不是文本的按钮,并且我还有一组单选按钮,我想控制在常规按钮上显示的图像。目前,单选按钮似乎没有更新我的photofilepath StringVar,因为无论选择的单选按钮如何,该按钮始终具有默认照片。这是我的(简化)代码:

root = Tk()  # Set up 
root.title("Test GUI")
gui.grid(column=0, row=0, sticky=(N, W, E, S))

photofilepath = StringVar()  # Set default photo
photofilepath.set("C:/Users/Ben/Pictures/Default photo.png")
photo = PhotoImage(file=photofilepath.get())

CalcButton = ttk.Button(gui, image=photo)
CalcButton.grid(column=3, row=2, columnspan=1)

# Set button photo
Photo1Rbutton = ttk.Radiobutton(gui, text="Photo 1", variable=photofilepath,
                                  value='C:/Users/Ben/Pictures/Photo 1.png')
Photo1Rbutton.grid(column=4, row=2, sticky=S)
Photo2Rbutton = ttk.Radiobutton(gui, text="Photo 2", variable=photofilepath,
                                  value='C:/Users/Ben/Pictures/Photo 2.png')
Photo2Rbutton.grid(column=4, row=3)

root.mainloop()

提前感谢您的帮助。

【问题讨论】:

  • 单选按钮不会(自动)执行PhotoImage(...) 来加载新图像,CalcButton[image] = photo 不会执行按钮上的图像。
  • 谢谢@furas 你也帮助我解决了我之前的问题。
  • 我正在创建完整的工作示例,因为您的示例不起作用;)例如,您有未知变量 gui :)

标签: python python-3.x tkinter


【解决方案1】:

您可以在Radiobutton 中使用command= 来分配将加载新图像并将它们放入标签的函数。

工作示例(您只需设置路径)

import tkinter as tk
from tkinter import ttk

# to easily change example
DEFAULT = "C:/Users/Ben/Pictures/Default photo.png"
PHOTO_1 = "C:/Users/Ben/Pictures/Photo 1.png"
PHOTO_2 = "C:/Users/Ben/Pictures/Photo 2.png"


def change_image():
    print(photo_filepath.get())

    photo = tk.PhotoImage(file=photo_filepath.get())
    calc_button['image'] = photo
    calc_button.image = photo # solution for garbage-collector problem. you have to assign PhotoImage object to global variable or class variable

    # - or -

    photo['file'] = photo_filepath.get()
    calc_button['image'] = photo


root = tk.Tk()  # Set up 
root.title("Test GUI")

photo_filepath = tk.StringVar()  # Set default photo
photo_filepath.set(DEFAULT)

photo = tk.PhotoImage(file=photo_filepath.get())

calc_button = ttk.Button(root, image=photo)
calc_button.grid(column=3, row=2, columnspan=1)

photo1_radiobutton = ttk.Radiobutton(root, text="Photo 1", variable=photo_filepath,
                                  value=PHOTO_1, command=change_image)
photo1_radiobutton.grid(column=4, row=2, sticky=tk.S)

photo2_radiobutton = ttk.Radiobutton(root, text="Photo 2", variable=photo_filepath,
                                  value=PHOTO_2, command=change_image)
photo2_radiobutton.grid(column=4, row=3)

root.mainloop()

【讨论】:

  • 感谢您的帮助,但这似乎对我不起作用,图像确实交换了,但它交换为透明/空白图像,给我留下了一个默认按钮。似乎只有默认图像有效。
  • 你试过photo['file'] = photo_filepath.get()。我忘记了PhotoImage 在函数中使用并分配给局部变量时可能会遇到垃圾收集器的问题。垃圾收集器删除图像,但它不应该。我更改了代码。
猜你喜欢
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 2017-01-16
相关资源
最近更新 更多