我们正在制作一个待办事项列表作为娱乐项目,在将列表带到不同函数的功能上遇到了难题。程序的目的是让用户按下“新建任务”按钮并输入内容,然后将字符串添加该列表,并通过 Listbox 显示出来。以下是到目前为止的代码。
(忽略 DelTask 函数,因为它仍在进行中)
from Tkinter import *
import Tkinter
import tkMessageBox
import sys
count = 0
class ToDoList:
def __init__(self):
#print testlist
self._count = 0
self.main_window = Tkinter.Tk()
#size
self.main_window.minsize(1000,800)
self.main_window.maxsize(1000,800)
#frames
self.title_frame = Tkinter.Frame(self.main_window)
#self.side_frame = Tkinter.Frame(self.main_window)
#labels
self.title = Tkinter.Label(self.title_frame, text = 'To Do List', font = ("Purisa",30))
self.title2 = Tkinter.Label(self.title_frame, text = 'By Kevin', font = ("Purisa",15))
#buttons
self.newtask_button = Tkinter.Button(self.main_window, text='New Task', command = self.NewTask, width=20)
self.newtask_button.grid()
self.deltask_button = Tkinter.Button(self.main_window, text='Delete Task', command = self.DelTask, width=20)
self.deltask_button.grid()
#execute
self.title.pack(side='top')
self.title2.pack(side='top')
self.title_frame.pack(side='top')
self.newtask_button.pack(padx=4, pady=4)
self.deltask_button.pack(padx=1, pady=1)
#list stuff
listbox = Listbox(self.main_window, width=100, height = 100, font=('Fixed',20) )
listbox.pack()
#print testlist
Tkinter.mainloop()
def NewTask(self):
self.newtask_window = Tkinter.Tk()
self.newtask_window.minsize(250,150)
self.newtask_window.maxsize(250,150)
#text
self.task_label = Tkinter.Label(self.newtask_window, text='Enter Task.')
self.task_label.pack()
#entry
self.task_entry = Tkinter.Entry(self.newtask_window, width=30)
self.task_entry.pack()
#button
self.task_button = Tkinter.Button(self.newtask_window, text='Ok', command = self.NewTaskCount, width = 20)
self.task_button.pack()
Tkinter.mainloop()
def NewTaskCount(self):
listbox = Listbox(self.main_window, width=100, height = 100, font=('Fixed',20) )
listbox.pack()
self._count += 1
self.newtask_window.destroy()
def DelTask(self):
tkMessageBox.showinfo('Title', 'Task Deleted')
program = ToDoList()
2、解决方案
收到问题描述后,给出的回答可以总结为以下几点:
- Tkinter 错误:该错误的部分原因是使用 Tkinter 的方式不正确。你应该始终创建一个 Tk 类实例,并在程序的生命周期中只调用一次 mainloop。
- 多个窗口:如果需要多个窗口,在创建 Tk 实例后,任何其他窗口都必须是 Toplevel 实例。
根据这些问题的总结,你可以从以下两个点修改代码:
-
Tkinter 类的实例化和销毁。
-
NewTask函数和NewTaskCount函数。
以下是修改后的代码:
def __init__(self):
self.main_window = Tk()
...
def NewTask(self):
self.newtask_window = Toplevel(self.main_window)
...
def NewTaskCount(self):
listbox = Listbox(self.main_window, width=100, height=100, font=('Fixed', 20))
listbox.pack()
self._count += 1
self.newtask_window.destroy()
program = ToDoList()
program.main_window.mainloop()
修改后的代码可以解决问题,但仍有一些可以改进的地方。例如,可以添加更多的错误处理来确保程序在各种情况下都能正常运行。还可以添加更多的功能,例如让用户能够编辑任务或完成任务。