我的问题是键入回车后文本框会自动生成一个空段
源码如下:
import tkinter as tk
import tkinter.messagebox
import threading
import time
import pygame
import os
from tkinter import ttk
def add_schedule(event=None):
schedule = text.get("1.0", "end-1c").strip()
text.delete("1.0", "end")
listbox.insert("end", schedule)
alarm_time = schedule.split()[0]
alarm_thread = threading.Thread(target=alarm, args=(alarm_time, schedule))
alarm_thread.start()
alarm_threads.append(alarm_thread)
with open("schedules.txt", "a") as f:
f.write(schedule + "\n")
def delete_schedule(event=None):
selected = listbox.curselection()
for index in reversed(selected):
listbox.delete(index)
alarm_threads[index].do_run = False
del alarm_threads[index]
def alarm(alarm_time, schedule):
t = threading.current_thread()
while getattr(t, "do_run", True):
current_time = time.strftime("%H:%M:%S")
if current_time == alarm_time:
threading.Thread(target=show_messagebox, args=(schedule,)).start()
pygame.mixer.init()
pygame.mixer.music.load(music_var.get())
pygame.mixer.music.play()
break
time.sleep(1)
def show_messagebox(schedule):
tk.messagebox.showinfo("Alarm", schedule)
def on_closing():
with open("schedules.txt", "w") as f:
for schedule in listbox.get(0, "end"):
f.write(schedule + "\n")
root.destroy()
root = tk.Tk()
root.title("Schedule Management")
style = ttk.Style()
style.configure("TButton", font=("Helvetica", 12), padding=10)
label = ttk.Label(root, text="Enter schedule (HH:MM:SS Description):")
label.pack()
text = tk.Text(root, height=3)
text.pack()
text.bind("" , add_schedule)
button_frame = ttk.Frame(root)
button_frame.pack()
add_button = ttk.Button(button_frame, text="Add", command=add_schedule)
add_button.pack(side="left")
delete_button = ttk.Button(button_frame, text="Delete", command=delete_schedule)
delete_button.pack(side="right")
music_label = ttk.Label(root, text="Select music:")
music_label.pack()
music_var = tk.StringVar(root)
music_files = [f for f in os.listdir() if f.endswith(".mp3")]
music_var.set(music_files[0])
music_optionmenu = ttk.OptionMenu(root, music_var, *music_files)
music_optionmenu.pack()
listbox = tk.Listbox(root, selectmode="extended")
listbox.pack(fill="both", expand=True)
alarm_threads = []
try:
with open("schedules.txt", "r") as f:
schedules = sorted(f.readlines(), key=lambda x: x.split()[0])
for line in schedules:
listbox.insert("end", line.strip())
alarm_time = line.split()[0]
if time.strptime(alarm_time, "%H:%M:%S") > time.localtime()[3:6]:
alarm_thread = threading.Thread(target=alarm, args=(alarm_time, line.strip()))
alarm_thread.start()
alarm_threads.append(alarm_thread)
except FileNotFoundError:
pass
root.bind("" , delete_schedule)
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
如下:
求解决措施
所以你希望是什么效果,是不要有空行吗?
如果是,那直接使用Entry就行了。