python - 从 .txt 文件中检索输入
问题描述
使用下面的 .txt 文件,如何创建一个 tkinter GUI,它将获取 txt 文件并为每一行代码创建一个新框架。是否可以在每个页面上为它们制作单独的按钮?
#Hello.txt
hi
hello
here
解决方案
通常,您希望有一些代码示例来说明您正在尝试做什么以及您在哪里被困在这里提出问题。
然而,这并不难想象,我想建立一个例子。
在这里,我创建了一个具有 2 个按钮和一个标签的 GUI。我只需使用跟踪变量在下一个或上一个索引处更新标签。如果我到达列表的开头或列表的末尾,按钮将不会做任何事情,除了打印到控制台您已到达末尾。
这个例子应该作为你想要做的事情的一个很好的基础。
我的main.py
python 文件和我的data.txt
文件在同一个目录中。
该data.txt
文件如下所示:
Row one in file.
Row two in file.
Row three in file.
代码是:
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.list_of_data_in_file = []
self.ndex = 0
with open("data.txt", "r") as data:
# Readlines() will convert the file to a list per line in file.
self.list_of_data_in_file = data.readlines()
self.lbl = tk.Label(self, text=self.list_of_data_in_file[self.ndex])
self.lbl.grid(row=0, column=1)
tk.Button(self, text="Previous", command=self.previous).grid(row=0, column=0)
tk.Button(self, text="Next", command=self.next).grid(row=0, column=2)
def previous(self):
# simple if statement to make sure we don't get errors when changing index on the list.
if self.ndex != 0:
self.ndex -= 1
self.lbl.config(text=self.list_of_data_in_file[self.ndex])
else:
print("No previous index")
def next(self):
# simple if statement to make sure we don't get errors when changing index on the list.
if self.ndex != (len(self.list_of_data_in_file) - 1):
self.ndex += 1
self.lbl.config(text=self.list_of_data_in_file[self.ndex])
else:
print("Reached end of list!")
if __name__ == "__main__":
App().mainloop()
推荐阅读
- c - 逗号分隔的结构元素是什么意思?
- machine-learning - 逻辑回归在二元分类任务中优于递归神经网络的原因可能是什么?
- javascript - 为新路由 reactJS 创建一个按钮
- javascript - 为什么 React Native Android 应用程序在调试模式下运行很慢?
- selenium-chromedriver - Appium 问题:java.io.IOException:流连接意外结束
- spring - 如何使用事务注释捕获错误?
- android - 是否可以支持自定义扩展文件?
- javascript - js promise - 如果条件满足,如何结束“then”执行,如果不满足,则继续下一个 then
- android - Flutter 用户应该运行“flutter pub get”而不是“pub get”
- c# - 使用反射在 MSTest 中获取异常消息或完整异常