如何使用单选按钮更新按钮内的照片?

时间:2016-10-28 21:08:43

标签: python python-3.x tkinter

我目前正在尝试学习如何使用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()

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以在command=中使用Radiobutton分配将加载新图片并将其放入标签的功能。

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

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