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

2024-09-29 23:21:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有一个按钮,它显示一个图像而不是文本,我也有一组单选按钮,我想控制哪些图像显示在常规按钮上。目前,单选按钮似乎没有更新我的photofilepathStringVar,因为无论选中了哪个单选按钮,该按钮始终具有默认照片。以下是我的(简化)代码:

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

提前谢谢你的帮助。在


Tags: pngguicolumnroot按钮usersgridrow
1条回答
网友
1楼 · 发布于 2024-09-29 23:21:02

您可以在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()

相关问题 更多 >

    热门问题