実現したいこと
pythonのtksheetを使ってexcelみたいの表を作成したい。
コードを表の外観等を規定する部分と入力値の検証等の部分の2ファイルに分割したい。
発生している問題・分からないこと
下記の第1案a_0.pyの様に一つのファイルに全て書くとコード中のcell_select関数は希望通り動作します。このcell_select関数を別ファイルにした第2案a_1.py,a_2.pyでは File "C:\PyPost\a_2.py", line 3, in cell_select
current_selection = self.sheet.get_currently_selected()
KeyError: 'sheet'のエラー発生しprint("aaaaaaa")部分も実行されません。
該当のソースコード
第1案 a_0.py from tksheet import Sheet import tkinter as tk class demo(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.frame = tk.Frame(self) self.frame.grid_columnconfigure(0, weight=1) self.frame.grid_rowconfigure(0, weight=1) self.sheet = Sheet(self.frame, data=[[f"Row {r}, Column {c}\nnewline1\nnewline2" for c in range(50)] for r in range(500)]) self.sheet.enable_bindings( "single_select", "rc_select", ) self.sheet.extra_bindings("cell_select", self.cell_select) self.frame.grid(row=0, column=0, sticky="nswe") self.sheet.grid(row=0, column=0, sticky="nswe") def cell_select(self, event=None): current_selection = self.sheet.get_currently_selected() print(current_selection) app = demo() app.mainloop() ------------------------------------- 第2案 a_1.py from tksheet import Sheet import tkinter as tk import a_2 class demo(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.frame = tk.Frame(self) self.frame.grid_columnconfigure(0, weight=1) self.frame.grid_rowconfigure(0, weight=1) self.sheet = Sheet(self.frame, data=[[f"Row {r}, Column {c}\nnewline1\nnewline2" for c in range(50)] for r in range(500)]) self.sheet.enable_bindings( "single_select", "rc_select", ) self.sheet.extra_bindings("cell_select", a_2.cell_select) self.frame.grid(row=0, column=0, sticky="nswe") self.sheet.grid(row=0, column=0, sticky="nswe") app = demo() app.mainloop() -------------------- a_2.py def cell_select(self, event=None): print("aaaaaaa") current_selection = self.sheet.get_currently_selected() print(current_selection) print("bbbbbbb")
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
ネットではtksheetの情報がほとんどありませんでした。
Excelの様に外枠が有り、行名、列名等が設定でき、行、列サイズ等も設定できる他のモジュールが有れば紹介ください
補足
特になし
self.sheet.extra_bindings("cell_select", a_2.cell_select)
を、以下に置き換えてみて下さい。
self.sheet.extra_bindings("cell_select", lambda _: a_2.cell_select(self))
コメントありがとうございます。(self)追加を試しましたがまだ解決できていません。
追加すると、画面表示と同時に
aaaaaaa
()
bbbbbbb
が表示されます。その後いろいろセルをクリックしても何の反応もありません。
試した結果を質問に追記しました。
手元の環境は Python 3.11.6/tksheet 6.3.5 ですが、例えば 5A のセルをクリックすると、
aaaaaaa
CurrentlySelectedClass(row=4, column=0, type_='cell')
bbbbbbb
と表示されます。
コメントありがとうございます。
大変失礼しました。大成功です!
self.sheet.extra_bindings("cell_select", lambda _: a_2.cell_select(self))の
末尾の(self)のみ追加しトライしました。lambda _に気が付きませんでした。
重ねて、ありがとうございました

回答2件
あなたの回答
tips
プレビュー