tkinter checkbutton 不同的图像

tkinter checkbutton different image

我想要一个基本上有我自己的开关图像的 tkinter 复选按钮,而不是默认的复选按钮。我在互联网上搜索了解决方案,但找不到任何东西。我认为 ttk 样式可能是可行的,但我不确定如何

尝试更改复选按钮中的 selectimage 选项,但毫无效果

编辑: 将 indicatoron 设置为 false,然后更改图像并选择图像有效

未选中状态需要设置image选项,选中状态需要设置selectimage选项。您还需要将 indicatoron 设置为 False 以便 tkinter 不显示默认指示器。

这是一个简单的例子:

import tkinter as tk
root = tk.Tk()

on_image = tk.PhotoImage(width=48, height=24)
off_image = tk.PhotoImage(width=48, height=24)
on_image.put(("green",), to=(0, 0, 23,23))
off_image.put(("red",), to=(24, 0, 47, 23))

var1 = tk.IntVar(value=1)
var2 = tk.IntVar(value=0)
cb1 = tk.Checkbutton(root, image=off_image, selectimage=on_image, indicatoron=False,
                     onvalue=1, offvalue=0, variable=var1)
cb2 = tk.Checkbutton(root, image=off_image, selectimage=on_image, indicatoron=False,
                     onvalue=1, offvalue=0, variable=var2)

cb1.pack(padx=20, pady=10)
cb2.pack(padx=20, pady=10)

root.mainloop()

ttk.Checkbutton 小部件的选项少于 tk.Checkbutton 小部件。例如。选项 selectimageindicatoron 选项不可用。

为了获得与 中所示相同的结果,进行了以下操作:

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
root['background'] = 'white'  # for linux distro

# Remove the indicator from a customised TCheckbutton style layout
s = ttk.Style()
s.layout('no_indicatoron.TCheckbutton',
         [('Checkbutton.padding', {'sticky': 'nswe', 'children': [
             # ('Checkbutton.indicator', {'side': 'left', 'sticky': ''}),
             ('Checkbutton.focus', {'side': 'left', 'sticky': 'w',
                                    'children':
                                    [('Checkbutton.label', {'sticky': 'nswe'})]})]})]
         )

on_image = tk.PhotoImage(width=48, height=24)
off_image = tk.PhotoImage(width=48, height=24)
on_image.put(("green",), to=(0, 0, 23, 23))
off_image.put(("red",), to=(24, 0, 47, 23))

var1 = tk.IntVar(value=1)
var2 = tk.IntVar(value=0)


# Define functions to check Checkbutton state to show the corrsponding image.
def cb1_state():
    if cb1.instate(['!disabled', 'selected']):
        cb1['image'] = on_image
        print(f'cb1-on_image {var1.get()}')
    else:
        cb1['image'] = off_image
        print(f'cb1-off_image {var2.get()}')
    print()


def cb2_state():
    if cb2.instate(['!disabled', 'selected']):
        cb2['image'] = on_image
        print(f'cb2-on_image {var2.get()}')
    else:
        cb2['image'] = off_image
        print(f'cb2-off_image {var2.get()}')
    print()


# Use the customised style and functions
cb1 = ttk.Checkbutton(root, image=off_image, onvalue=1, offvalue=0,
                      variable=var1, style='no_indicatoron.TCheckbutton',
                      command=cb1_state)
cb2 = ttk.Checkbutton(root, image=off_image, onvalue=1, offvalue=0,
                      variable=var2, style='no_indicatoron.TCheckbutton',
                      command=cb2_state)

cb1.pack(padx=20, pady=10)
cb2.pack(padx=20, pady=10)

root.mainloop()