【问题标题】:Making a button in a GUI that will remove contents of a .txt file在 GUI 中创建一个按钮,将删除 .txt 文件的内容
【发布时间】:2021-05-01 22:36:41
【问题描述】:

您好,我正在尝试为应用程序制作一个清除按钮。当我单击清除按钮时,什么也没有发生(这可能是因为我知道 python)。我到处寻找,但找不到答案,所以如果有人可以帮助我,那就太好了(顺便说一句,我发布了我编写的所有代码)。

import tkinter as tk
from tkinter import filedialog, Text
import os

root = tk.Tk()
root.title('Application Launcher')
apps = []

if os.path.isfile('save.txt'):
    with open('save.txt', 'r') as f:
        tempApps = f.read()
        tempApps = tempApps.split(',')
        apps = [x for x in tempApps if x.strip()]


def addApp():

    for widget in frame.winfo_children():
        widget.destroy()

    filename= filedialog.askopenfilename(initialdir="/", title="Select File",
                                        filetypes=(("executables", "*.exe"), ("all files", "*.*")))
    apps.append(filename)
    print(filename)
    for app in apps:
        label = tk.Label(frame, text=app, bg="gray")
        label.pack()

def runApps():
    for app in apps:
        os.startfile(app)

def clearApps():
    if 'save.txt' in os.path.("save.txt")():
        os.remove('save.txt')
        tk.messagebox.showinfo('Removed!', 'Successfully Removed!')
    else:
        tk.messagebox.showerror('Error!', 'File not found!')


canvas = tk.Canvas(root, height=500, width=500, bg="#262e2e")

canvas.pack()

frame = tk.Frame(root, bg="#262e2e")
frame.place(relwidth=0.7, relheight=0.7, relx=0.1, rely=0.1)

openFile = tk.Button(root, text="Open File", padx=10, pady=5, fg="black", bg="white", command=addApp)

openFile.pack()

runApps = tk.Button(root, text="Run Apps", padx=10, 
                    pady=5, fg="black", bg="white", command= runApps)

runApps.pack()

clearApps = tk.Button(root, text="Clear")

clearApps.pack(side=tk.LEFT)

for app in apps:
    label = tk.Label(frame, text=app)
    label.pack()

root.mainloop()

with open('save.txt', 'w') as f:
    for app in apps:
        f.write(app + ',')

【问题讨论】:

  • 你为什么说有问题? ...与其说I don't know what's wrong,不如说实际发生的事情
  • os.remove deletes 整个文件,这是你想要的吗?
  • @jsotola 完成我更改了标题

标签: python user-interface tkinter button


【解决方案1】:

如果您说的是清除应用列表,则说明您没有为清除按钮分配命令。

clearApps = tk.Button(root, text="Clear", command=clearApps)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 2017-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多