目標
前回は、Gtk.AlertDialogで①ユーザーに情報を表示する方法を紹介しました。今回は、Gtk.AlertDialogを使用して、②ユーザーに選択を要求するものを作成する方法を紹介します。
例:ユーザーに選択を要求するGtk.AlertDialog。「はい」と「いいえ」が選択可能。
Gtk.AlertDialogの定義
選択肢を持ったGtk.AlertDialogの作成
Gtk.AlertDialogに選択肢(ボタン)を追加するには、以下の作業をおこないます。
1. プロパティbuttonsでボタンを指定する。
2. プロパティdefault_button、cancel_buttonを指定する。
このGtk.AlertDialogは、メソッドchooseを使用して表示します。chooseでは、ボタンが押された場合に処理をおこなう関数(ここでは、self.alert_choose)を指定します。
alertdialog = Gtk.AlertDialog(
buttons=['はい', 'いいえ'],
default_button=0,
cancel_button=1,
detail='こんにちは',
message='メッセージです。',
modal=True,
)
alertdialog.choose(self, None, self.alert_choose)
選択されたものに対しての処理
Gtk.AlertDialogではメソッドchoose_finishにより選択したボタンの番号を取得します。取得した番号ごとに、その番号にあった処理をおこないます。
def alert_choose(self, alertdialog, result):
num = alertdialog.choose_finish(result)
match num:
case 0:
print('「はい」もしくはEnterキーが押されました。')
case 1:
print('「いいえ」もしくはESCキーが押されました。')
※ match文は、python3.10より使用可能になりました。
サンプルプログラム
以下のプログラムを実行すると、左図のようなウィンドウが表示されます。ウィンドウ内の’Gtk.AlertDialogの表示’ボタンを押すと、右図のようなGtk.AlertDialogが表示されます。
Gtk.AlertDialogのどちらかのボタンを押すと、ボタンごとに指定したメッセージをターミナルに表示してGtk.AlertDialogは閉じます。
import gi
gi.require_version('Gtk', '4.10')
from gi.repository import Gtk
APPID = 'com.github.taniyoshima.g4_fblog2_alertdialog2'
class Gtk4TestTest(Gtk.Window):
def __init__(self, app):
Gtk.Window.__init__(
self, application=app, title='AlertDialog Test2',
default_width=400, default_height=80)
button = Gtk.Button(
label='Gtk.AlertDialogの表示',
margin_top=20, margin_bottom=20,
margin_start=20, margin_end=20,
)
button.connect('clicked', self.on_button_clicked)
self.set_child(button)
def on_button_clicked(self, button):
alertdialog = Gtk.AlertDialog(
buttons=['はい', 'いいえ'],
default_button=0,
cancel_button=1,
detail='こんにちは',
message='メッセージです。',
modal=True,
)
alertdialog.choose(self, None, self.alert_choose)
def alert_choose(self, alertdialog, result):
num = alertdialog.choose_finish(result)
match num:
case 0:
print('「はい」もしくはEnterキーが押されました。')
case 1:
print('「いいえ」もしくはESCキーが押されました。')
class Gtk4TestApp(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self, application_id=APPID)
def do_activate(self):
window = Gtk4TestTest(self)
window.present()
def main():
app = Gtk4TestApp()
app.run()
if __name__ == '__main__':
main()