用python的tkinter实现点击一个按钮,打开一个.txt格式的记事本
时间: 2024-02-13 11:00:05 浏览: 36
好的,下面是实现的代码:
```python
import tkinter as tk
import os
def open_notepad():
filename = "example.txt" # 修改为你要打开的文件名
os.system(f"notepad.exe {filename}")
root = tk.Tk()
root.title("打开记事本")
button = tk.Button(root, text="打开记事本", command=open_notepad)
button.pack()
root.mainloop()
```
在这个示例中,我们创建了一个 `open_notepad` 函数,它使用 `os` 模块调用系统的记事本程序打开指定的文件(这里我们指定为 `example.txt`,你可以根据需要修改)。然后我们创建了一个窗口,添加了一个名为“打开记事本”的按钮,点击该按钮将调用 `open_notepad` 函数打开记事本。
注意:在使用 `os.system` 执行命令时,需要指定完整的文件路径,或者将文件放在当前工作目录下。
相关问题
用python的tkinter库写一个记事本程序。
好的,下面是一个使用 Python Tkinter 库制作的简单记事本程序的代码:
```
import tkinter as tk
def save_text():
text = text_widget.get("1.0", "end-1c")
with open("notes.txt", "w") as file:
file.write(text)
root = tk.Tk()
root.title("简单记事本")
text_widget = tk.Text(root, height=20, width=50)
text_widget.pack()
save_button = tk.Button(root, text="保存", command=save_text)
save_button.pack()
root.mainloop()
```
这段代码创建了一个 Tkinter 的 GUI,其中包含一个文本框和一个保存按钮。按钮被点击时,文本框中的内容将被保存到一个名为 "notes.txt" 的文件中。
用Python的tkinter实现:假如屏幕上出现了一个人名,点击‘加分’按钮,就可以给这个人加分,加分的数据储存在一个.txt格式的记事本里
好的,以下是实现该功能的代码:
```python
import tkinter as tk
class AddScoreApp:
def __init__(self):
self.name = "" # 存储人名
self.score = 0 # 存储分数
self.filepath = "scores.txt" # 存储分数的文件路径
self.load_scores() # 读取之前的分数记录
self.root = tk.Tk()
self.root.title("加分")
self.root.geometry("300x150")
self.name_label = tk.Label(self.root, text="人名:")
self.name_label.pack()
self.name_entry = tk.Entry(self.root)
self.name_entry.pack()
self.score_label = tk.Label(self.root, text="分数:" + str(self.score))
self.score_label.pack()
self.add_button = tk.Button(self.root, text="加分", command=self.add_score)
self.add_button.pack()
self.root.mainloop()
def add_score(self):
self.name = self.name_entry.get() # 获取人名
if self.name != "":
self.score += 1 # 加1分
self.score_label.config(text="分数:" + str(self.score)) # 更新分数显示
self.save_scores() # 保存分数记录
else:
tk.messagebox.showerror("错误", "请输入人名!")
def load_scores(self):
try:
with open(self.filepath, "r") as f:
lines = f.readlines()
for line in lines:
name, score = line.strip().split(",")
if name == self.name:
self.score = int(score)
self.score_label.config(text="分数:" + str(self.score)) # 更新分数显示
except FileNotFoundError:
pass
def save_scores(self):
with open(self.filepath, "a") as f:
f.write("{},{}\n".format(self.name, self.score))
if __name__ == "__main__":
app = AddScoreApp()
```
这个应用程序由一个 AddScoreApp 类组成,包含了一个输入框、一个标签、一个按钮和一个分数记录文件。用户在输入框中输入人名,然后点击按钮,就会给该人加1分,并将分数记录保存在文件中。如果用户输入了之前已经加过分的人名,那么程序会自动读取之前的分数记录,并在标签中显示出来。注意,这个程序只是一个简单的示例,实际应用中需要对输入进行更多的验证和处理。