我有一个python程序,用于访问数据库以查找需要在屏幕上显示的内容。它的目的是显示何时可以提取某人的订单。我有所有代码来获取数据并将其显示在窗口上。但是,我需要每60秒重新查询一次数据库,因为有些订单会被拿走,并且需要从列表中消失,还有一些需要添加。我只是不知道该怎么做,因为一旦调用了app.mainloop(),它就需要人与窗口的交互才能使事情发生。任何帮助将不胜感激...很抱歉长期困扰!
答案 0 :(得分:2)
以下是我汇总的一个示例,向您展示了如何使用after()
检查这么多秒来更新跟踪器的一些基础知识。
如果您有任何疑问,请告诉我。
import tkinter as tk
class Example(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.geometry("600x400")
self.current_ticket_number = 1
self.data = [[97, "Mike"], [98, "Kaite"], [99, "Tom"]]
self.display_frame = tk.Frame(self)
self.display_frame.grid(row=2, column=0, columnspan=3, sticky="nsew")
self.lbl1 = tk.Label(self, text="Next ticket number: {}".format(self.current_ticket_number))
self.lbl1.grid(row=0, column=0)
self.lbl2 = tk.Label(self, text="Customer Name: ".format(self.current_ticket_number))
self.lbl2.grid(row=0, column=1)
self.entry1 = tk.Entry(self)
self.entry1.grid(row=0, column=2)
tk.Button(self, text="Refresh List", command=self.refresh).grid(row=1, column=0, pady=5)
tk.Button(self, text="Submit new ticket", command=self.new_ticket).grid(row=1, column=1, pady=5)
self.timed_refresh()
def new_ticket(self):
x = self.entry1.get().strip()
if x != "":
self.data.append([self.current_ticket_number, x])
#self.refresh() # you could do self.refresh() here if you want to update as soon as you create a ticket
#I left it out though so you can see how after() works below.
if self.current_ticket_number >= 99:
self.current_ticket_number = 1
else:
self.current_ticket_number += 1
def refresh(self):
self.display_frame.destroy()
self.display_frame = tk.Frame(self)
self.display_frame.grid(row=2, column=0, columnspan=3, sticky="nsew")
for ndex, item in enumerate(self.data):
tk.Label(self.display_frame, text=r"Order #{} is ready for {}.".format(item[0], item[1])).grid(row=ndex, column=1)
tk.Button(self.display_frame, text=r"Remove Ticket".format(item[0], item[1]), command=lambda x=ndex: self.remove_ticket(x)).grid(row=ndex, column=0)
def remove_ticket(self, ndex):
self.data.pop(ndex)
self.refresh()
def timed_refresh(self):
#this after statement is set for every 6 seconds
self.after(6000, self.timed_refresh)
self.refresh()
if __name__ == "__main__":
Example().mainloop()
答案 1 :(得分:0)
这就是我最后得到的。似乎在做我需要做的事。感谢您的所有帮助,一切就绪。
class Application(tk.Frame):
def __init__(self,master=None):
self.createWidgets()
def createWidgets(self):
tk.Frame.__init__(self)
self.pack()
for b in range(0,int(len(myItems)/2)):
#print (myItems[b])
self.btn = tk.Button(self)
self.btn["text"] = myItems[b,0]
# self.btn["command"] = (lambda tck=b, binst=btn : pickUp(tck, binst))
# self.btn["command"] = lambda ticketNo=myItems[b,1] : self.pickUp(ticketNo)
self.btn.pack(fill='x')
def pp(self) :
#print('Im in pp')
self.destroy()
getArrowDataAndUpdateSQLite()
myItems = getDisplayData()
app.createWidgets()
app.master.after(30000, self.pp)
app = Application()
app.master.title('Customer Order Status')
app.master.after(30000,app.pp)
app.mainloop()