以下代码出现错误,其中"添加任务"按钮将通过在2个任务之间创建空格将空输入添加到列表框中。有没有办法在不可能发生的地方编码?我希望列表框中的列表是连续的,每个任务一个接一个地出现。我不明白为什么会这样。它是python的一部分吗?再次感谢。
import tkinter as tk
def main():
root = tk.Tk()
root.geometry("350x450")
root.title("basic window")
root.config(background="azure")
app = Application (root)
root.mainloop()
class Application(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, bg="yellow", bd=2, relief=tk.RIDGE)
self.parent = parent
self.initUI()
def initUI(self):
self.pack(fill="both", expand=1)
#widget layout
self.listbox = tk.Listbox(self, bd=2, relief=tk.SUNKEN, height="15")
self.listbox.grid(row=0, column=0, sticky="w", padx=5, pady=5)
self.entry=tk.Entry(self, width=19)
self.entry.grid(row=1, stick="w", padx=5)
self.button1=tk.Button(self, text="add task", command=self.update)
self.button1.grid(row=1, column=1, sticky="w", padx=5)
self.label=tk.Label(self, text="stats", bg="yellow")
self.label.grid(row=0, column=1, sticky="n")
#programing
def update(self):
self.listbox.insert("end", self.entry.get())
self.entry.delete(0, "end")
if __name__ == '__main__':
main()
答案 0 :(得分:0)
update(self)
中,您需要测试self.entry.get()
是否包含空字符串;如果是,请跳过更新。
import tkinter as tk
class Application(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, bg="yellow", bd=2, relief=tk.RIDGE)
self.parent = parent
self.initUI()
def initUI(self):
self.pack(fill="both", expand=1)
#widget layout
self.listbox = tk.Listbox(self, bd=2, relief=tk.SUNKEN, height="15")
self.listbox.grid(row=0, column=0, sticky="w", padx=5, pady=5)
self.entry=tk.Entry(self, width=19)
self.entry.grid(row=1, stick="w", padx=5)
self.button1=tk.Button(self, text="add task", command=self.update)
self.button1.grid(row=1, column=1, sticky="w", padx=5)
self.label=tk.Label(self, text="stats", bg="yellow")
self.label.grid(row=0, column=1, sticky="n")
#programing
def update(self):
if self.entry.get() != '':
self.listbox.insert("end", self.entry.get())
self.entry.delete(0, "end")
def main():
root = tk.Tk()
root.geometry("350x450")
root.title("basic window")
root.config(background="azure")
app = Application (root)
root.mainloop()
if __name__ == '__main__':
main()
答案 1 :(得分:0)
def update(self):
if not self.entry.get()== "": #.get gets the value thgat the entry contains
self.listbox.insert("end", self.entry.get())
self.entry.delete(0, "end")
另外在旁注中我建议使用更好的名称,例如代替self.entry
使用self.intput_txt
,当我制作对象时,我倾向于使用_txt
或_lbl
ectra因为它使一眼就能看出它是什么类型的物体