怎么将text组件换成text文件 def show_diary(self): # 创建新窗口 self.show_window = tk.Toplevel(self.master) self.show_window.title("记事本内容") # 设置子窗口大小为300x300,并让窗口居中显示 window_width = 300 window_height = 300 screen_width = self.show_window.winfo_screenwidth() screen_height = self.show_window.winfo_screenheight() x_coordinate = int((screen_width - window_width) / 2) y_coordinate = int((screen_height - window_height) / 2) self.show_window.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}") # 创建 Text 组件 text_widget = tk.Text(self.show_window) text_widget.pack(fill='both', expand=True) # 添加日记内容到 Text 组件中 for i, entry in enumerate(diary): entry_with_number = f"{i + 1}. {entry}" text_widget.insert(tk.END, entry_with_number + '\n\n')
时间: 2024-03-12 10:47:41 浏览: 37
你可以使用Python的文件操作来打开并读取文本文件的内容,然后将其添加到Text组件中。以下是示例代码:
```python
def show_diary(self):
# 创建新窗口
self.show_window = tk.Toplevel(self.master)
self.show_window.title("记事本内容")
# 设置子窗口大小为300x300,并让窗口居中显示
window_width = 300
window_height = 300
screen_width = self.show_window.winfo_screenwidth()
screen_height = self.show_window.winfo_screenheight()
x_coordinate = int((screen_width - window_width) / 2)
y_coordinate = int((screen_height - window_height) / 2)
self.show_window.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")
# 创建 Text 组件
text_widget = tk.Text(self.show_window)
text_widget.pack(fill='both', expand=True)
# 读取文本文件内容并添加到 Text 组件中
with open('diary.txt', 'r') as f:
diary = f.readlines()
for i, entry in enumerate(diary):
entry_with_number = f"{i + 1}. {entry}"
text_widget.insert(tk.END, entry_with_number + '\n\n')
```
在这个示例中,我们使用了Python的`open()`函数来打开名为'diary.txt'的文本文件,并使用`readlines()`方法将其内容读取到一个列表中。然后,我们使用for循环将每个条目添加到Text组件中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)