3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Python】CustomTkinter でコンボボックスの選択肢を動的に変化させる

Last updated at Posted at 2022-12-18

やりたいこと

CustomTkinter でコンボボックスを2つ作成し、コンボボックス1の選択に連動して、コンボボックス2の値が変化するようにしたかった。

例えば、Combobox_1 に西暦・和暦(令和)、Combobox_2 に年を選択するとき、西暦が選択された場合は年の選択肢が「2019年」「2020年」「2021年」「2022年」となるようにし、和暦が選択された場合は年の選択肢が「元年」「2年」「3年」「4年」となるようにしたかった。

実装

import customtkinter as ctk

dict = {'西暦': ['2019年', '2020年', '2021年', '2022年'], 
        '令和': ['元年', '2年', '3年', '4年']}

ctk.set_appearance_mode("system")
ctk.set_default_color_theme("blue")

app = ctk.CTk()
app.geometry("290x110")
app.title("テストプログラム")
app.resizable(False, False)

def cb1_selected(event):
    combobox_2.configure(values=dict[combobox_1.get()])
    combobox_2.set(dict[combobox_1.get()][0])

combobox_1 = ctk.CTkComboBox(app, values=list(dict.keys()), command=cb1_selected, width=100)
combobox_1.pack(pady=10, padx=10)
combobox_1.set("西暦")
combobox_1.place(x=35, y=35)

combobox_2 = ctk.CTkComboBox(app, values=dict[combobox_1.get()], width=100)
combobox_2.pack(pady=10, padx=10)
combobox_2.place(x=155, y=35)

app.mainloop()

実行結界

下記のとおり、コンボボックス1(西暦・和暦)の選択に連動して、コンボボックス2(年)の値が変化するようになっています。

Screenshot 2022-12-18 17.54.04.png
Screenshot 2022-12-18 17.54.41.png

解説

コンボボックス1(combobox_1)で選択できる値(values)には、辞書のキーを設定します。
また、コンボボックス1のコールバック関数として cb1_selected 関数を指定します。

dict = {'西暦': ['2019年', '2020年', '2021年', '2022年'], 
        '令和': ['元年', '2年', '3年', '4年']}
...
combobox_1 = ctk.CTkComboBox(app, values=list(dict.keys()), command=cb1_selected, width=100)

コンボボックス1が選択されたら cb1_selected 関数がコールされ、下記のコードが実行されます。ここでは combobox_1.get() の値に基づいて、コンボボックス2の値を辞書で指定します。

def cb1_selected(event):
    combobox_2.configure(values=dict[combobox_1.get()])
    combobox_2.set(dict[combobox_1.get()][0])
3
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?