質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Tkinter

Tkinterは、GUIツールキットである“Tk”をPythonから利用できるようにした標準ライブラリである。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

1019閲覧

Python(TkInter):コマンドボタンのマウス操作では無事当該アプリを閉じられるが、リターンキー操作ではエラーになる。リターンキーにバインドさせるコマンド定義方法が分からない

saya24

総合スコア222

Tkinter

Tkinterは、GUIツールキットである“Tk”をPythonから利用できるようにした標準ライブラリである。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2020/05/23 04:41

編集2020/05/23 05:28

TkiInterのGUI開発で、分からないことがあるので ご教示ください。(下記コードはPythonの開発環境に丸々貼りつければ一応動作します)

下記コードの ★☆★引数不足みたいなエラーが生じます!★☆★ の部分で エラーとなってしまいます。

Error

1return self.func(*args) 2TypeError: quit() takes 1 positional argument but 2 were given

フォーム上の一つのボタンについて、カーソル操作すれば 無事設定しているコマンドが働き 当該アプリケーションが終了となってくれます。
しかし、エンターキーで操作すると、エラーとなってしまいます。単純に同じコマンド記述を リターンキーにバインドさせれば解決すると思っていたのですが。

どういう対策を施せばよろしいのでしょうか? 今までだったら 関数側の仮引数部分でevent=Noneと記述することで回避できていたような....

Python

1from tkinter import * 2import tkinter.ttk as ttk 3import tkinter.scrolledtext as tksc 4import math 5 6class Apprication(ttk.Frame): 7 8 def __init__(self, app): 9 super().__init__(app) 10 self.pack() 11 12 btn1 = ttk.Button(self, text="Sub", command=self.openDialog) 13 btn1.bind('<Return>', self.openDialog) 14 btn1.grid(row=1, column=0) 15 btn1.focus_set() 16 17 btn2 = ttk.Button(self, text="Quit", command=app.quit) #★マウス操作では閉じることができます★ 18 btn2.bind('<Return>', app.quit) #★☆★引数不足みたいなエラーが生じます!★☆★ 19 btn2.grid(row=2, column=0) 20 21 self.menu() 22 23 24 25 def focus_next(self, event): 26 event.widget.tk_focusNext().focus() 27 return "break" 28 29 30 31 def menu(self): 32 menu_top = Menu(app) 33 menu_file = Menu(menu_top, tearoff=False) 34 menu_open = Menu(menu_top, tearoff=False) 35 36 app.configure(menu=menu_top, bg="#F0FFFF") 37 38 menu_top.add_cascade (label='File(F)', menu=menu_file, underline=0) 39 40 menu_file.add_cascade(label='Open(O)', underline=0, menu=menu_open) 41 menu_open.add_command(label='Sub(S)', underline=0, command=self.openDialog) 42 menu_file.add_command(label='Quit(Q)',underline=0, command=app.quit) #★メニューからは閉じることができます★ 43 44 45 46 47 48 # 子画面開く 49 def openDialog(self, event=None): 50 51 self.dialog = Toplevel(self) 52 self.dialog.title("Sub Menu") 53 54 #フォームサイズを実行端末から導き、ド真中に配置表示 55 lw = math.ceil(ww * 0.408) 56 lh = math.ceil(wh * 0.477) 57 self.dialog.geometry(str(lw)+"x"+str(lh)+"+"+str(int(ww/2-lw/2))+"+"+str(int(wh/2-lh/2)) ) 58 59 self.dialog.configure(bg="#F0FFFF") 60 self.dialog.resizable(0,0) 61 self.dialog.protocol('WM_DELETE_WINDOW', (lambda: 'pass')()) 62 63 # 当該ダイアログのカーソルを変更し、関数側でもカーソルを変更できるように 64 self.dialog['cursor'] = 'hand2' 65 self.this = self.dialog 66 67 # modalに 68 self.dialog.grab_set() 69 70 # コンボボックス 71 db = {1:"AAA",2:"BBB",3:"CCC"} 72 self.v1 = StringVar() 73 cmbox1 = ttk.Combobox(self.dialog, takefocus=1, width=5, justify=CENTER, values=list(db.keys()), state='readonly', textvariable=self.v1) 74 cmbox1.bind('<<ComboboxSelected>>', self.cmbox1_selected) 75 cmbox1.grid(row=0, column=0, padx=(10, 0), pady=(10,0), sticky=W+E) 76 cmbox1.focus_set() 77 78 79 # テキストボックス 80 self.txt1 = Entry(self.dialog, state="readonly", takefocus=1) 81 self.txt1.grid(row=0, column=1, columnspan=7, sticky=W+E, pady=(10,0)) 82 83 84 # 入力枠 85 self.scrtxt1 = tksc.ScrolledText(self.dialog, bg="black", fg="orange", font=("Helvetica",11), insertbackground="orange", blockcursor=True, height=6, state="disable", takefocus=1) 86 self.scrtxt1.bind("<Leave>", self.scrtxt1_Chk) 87 self.scrtxt1.grid(row=2, column=0, columnspan=11, sticky=W+E, padx=10) 88 self.scrtxt1.bind("<Tab>", self.focus_next) 89 90 # 実行ボタン 91 self.btn1 = Button(self.dialog, text='Execute', width=10, state=DISABLED, takefocus=1) 92 self.btn1.grid(row=3, columnspan=11, pady=(0, 20), sticky=N) 93 94 95 # 閉じるボタン 96 btn3 = Button(self.dialog, text='Quit', command=self.closeDialog, width=10, takefocus=1) 97 btn3.grid(row=5, column=10, pady=10, padx=(0,10)) 98 99 100 self.dialog.grid_rowconfigure(1, weight=1) 101 self.dialog.grid_rowconfigure(3, weight=1) 102 self.dialog.grid_columnconfigure(2, weight=1) 103 104 105 106 107 # 子画面閉じる 108 def closeDialog(self): 109 self.dialog.destroy() 110 111 112 # コンボボックス選択値をテキストボックス表示 113 def cmbox1_selected(self, event): 114 self.txt1['state'] = 'normal' 115 self.txt1.delete(0, END) 116 self.txt1.insert(END, self.v1.get()) 117 self.txt1['state'] = 'readonly' 118 119 self.scrtxt1['state'] = 'normal' 120 self.btn1_Enable() 121 122 123 # 入力枠チェック 124 def scrtxt1_Chk(self, event): 125 self.btn1_Enable() 126 127 128 # 実行ボタンの有効化 129 def btn1_Enable(self): 130 if (self.scrtxt1.get('1.0', 'end -1c') != ""): 131 self.btn1['state'] = 'normal' 132 else: 133 self.btn1['state'] = 'disable' 134 135 136if __name__ == '__main__': 137 138 #世間でいうrootをappとしています 139 app = Tk() 140 141 #実行端末の画面サイズを取得 142 ww = app.winfo_screenwidth() 143 wh = app.winfo_screenheight() 144 145 app.update_idletasks() 146 147 #フォームサイズを実行端末から導き、ド真中に配置表示 148 lw = math.ceil(ww * 0.208) 149 lh = math.ceil(wh * 0.277) 150 app.geometry(str(lw)+"x"+str(lh)+"+"+str(int(ww/2-lw/2))+"+"+str(int(wh/2-lh/2)) ) 151 152 #タイトルを指定 153 app.title("Main Menu") 154 155 #フォームの最大化、×ボタン操作を無効化 156 app.resizable(0,0) 157 #app.protocol('WM_DELETE_WINDOW', (lambda: 'pass')()) 158 159 # カーソル変更 160 app["cursor"] = "hand2" 161 162 163 164 165 menu_top = Menu(app) 166 menu_file = Menu(menu_top, tearoff=False) 167 menu_open = Menu(menu_top, tearoff=False) 168 169 app.configure(menu=menu_top, bg="#F0FFFF") 170 171 menu_top.add_cascade (label='File(F)', menu=menu_file, underline=0) 172 173 menu_file.add_cascade(label='Open(O)', underline=0, menu=menu_open) 174 menu_open.add_command(label='Sub(S)', underline=0, command="app.openDialog") 175 menu_file.add_command(label='Quit(Q)',underline=0, command=app.quit) #★メニューからは閉じることができます★ 176 177 178 179 180 # フレームを作成する 181 frame = Apprication(app) 182 # 格納したTkインスタンスのmainloopで画面を起こす 183 app.mainloop()

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

bind で登録した関数には、引数 event が渡ります。
event=None で回避できたのとは逆の状況ですね。
関数定義なく済ませたい場合は、

bind('<Return>', lambda _: app.quit())

quit()の呼び出しの括弧は忘れずに。


def quit(event): app.quit() btn2.bind('<Return>', quit)
  • event -> _ 引数は使わないので適当な _
  • 無名関数なので名前を省略 def quit -> lambda

とすると、lambda 式 lambda _: app.quit() が導けます。

投稿2020/05/23 07:01

teamikl

総合スコア8664

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

saya24

2020/05/23 07:24

いつもすみません、しかも親切に2パターンを示して頂きましてありがとうございます。 ろくにlamda式も理解できていないのに、関数定義不要なlamdaのほうを使わせて頂きます。 お陰様で着々と作りたいものが仕上がってきました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問