teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

別ファイルに分離、関数名を元コードに近づけました

2022/10/28 03:17

投稿

teamikl
teamikl

スコア8817

answer CHANGED
@@ -3,23 +3,45 @@
3
3
  サンプルコードとして回答します
4
4
 
5
5
  ```python
6
+ # to_json.py
7
+
8
+ def output(line):
9
+ # 実態がわからないため、値に対して何も変更しない 関数として実装。
10
+ return line
11
+
12
+
13
+ # GUIから再利用するために、「ジェネレーター」として実装
14
+ def read_file(filepath):
15
+ with open(filepath, encoding="utf-8") as stream:
16
+ for line in stream:
17
+ yield output(line)
18
+
19
+ # to_json.py を直接呼び出した場合は、ファイル内容をprintで出力
20
+ def main(filepath):
21
+ for line in read_file(filepath):
22
+ print(line)
23
+
24
+ if __name__ == "__main__":
25
+ import sys
26
+ main(sys.argv[1])
27
+
28
+ ```
29
+
30
+ ```python
31
+ # main.py
32
+
6
33
  import tkinter as tk
7
34
  from tkinter import ttk
8
35
  from tkinter.scrolledtext import ScrolledText
9
36
  from functools import partial
37
+ import to_json
10
38
 
11
- # 別ファイルに「ジェネレーター」として実装
12
- # ここではテスト用の仮実装として、数値の文字列を返します。
13
- def to_json():
14
- for num in range(200):
15
- yield f"{num}"
16
39
 
17
-
18
- def output(button, text, freq=20):
40
+ def calc(button, text, freq=20):
19
41
  # 処理中はボタンを押せないようにする
20
42
  button.state(["disabled"])
21
43
 
22
- stream = to_json()
44
+ stream = to_json.read_file("test.txt") # ※ "test.txt" ファイルを用意する
23
45
 
24
46
  for lineno, line in enumerate(stream, start=1):
25
47
  text.insert(tk.END, f"{lineno:04} ", "lineno")
@@ -40,7 +62,7 @@
40
62
  text.tag_config("lineno", foreground="#AAAAAA")
41
63
  text.pack(fill=tk.BOTH, expand=tk.YES)
42
64
  button = ttk.Button(root, text="Output")
43
- button.config(command=partial(output, button, text))
65
+ button.config(command=partial(calc, button, text))
44
66
  button.pack()
45
67
  root.mainloop()
46
68