简体   繁体   English

在GUI中运行sql查询时,ttk进度栏停止

[英]ttk progress bar stops whilst running sql query within GUI

I'm building a GUI which at some point(s) will query a SQL database. 我正在构建一个GUI,该GUI在某些时候将查询SQL数据库。 Whilst the query is running, I wanted to show the user an indeterminate progress bar (ttk) which would indicate this. 查询正在运行时,我想向用户显示一个不确定的进度条(ttk),该进度条将指示这一情况。 See below for simple example. 请参阅下面的简单示例。

from Function_Sheet import *
from Tkinter import *
import ttk
root = Tk()

s = ttk.Style()
s.theme_use('clam')
s.configure('red.Horizontal.TProgressbar', foreground='red', background='red')
mpb2 = ttk.Progressbar(root,style='red.Horizontal.TProgressbar', orient ='horizontal', length = 200, mode ='indeterminate')
mpb2.pack()
mpb2.start(1)
print 'query not done'
cursor = SolvittConnect(<SQL HERE>)
print 'query done'
root.mainloop()

Unfortunatley the query seems to run even before the root window is loaded. 不幸的是,查询似乎在加载根窗口之前就已运行。

How can I show the moving progress bar WHILST the query is being executed? 我怎样才能显示正在执行查询的移动进度条?

Any feedback would be appreciated. 对于任何反馈,我们都表示感谢。

For tkinter to draw anything, it must be in the mainloop. 对于tkinter画任何东西,它必须在主循环。 The mainloop is exactly as it sounds- an infinite loop which handles events. mainloop确实像听起来那样-处理事件的无限循环。 As such, commands after the mainloop are not done until the mainloop completes. 这样,直到主循环完成后,主循环之后的命令才执行。

To solve your issue, you need to setup the SQL query to happen in the mainloop while the GUI updates. 要解决您的问题,您需要将SQL查询设置为在GUI更新时在主循环中进行。 Do this by setting up an after call- it will be a lambda probably, so this is a good time to swap to classes, since they allow you to call a method from an after and that method can set a class variable 通过设置一个after调用来做到这一点-可能是lambda,所以这是交换类的好时机,因为它们允许您从after调用一个方法,并且该方法可以设置类变量

class ...
    ...
    def __init__(self):
        root=Tk()
        ...
        mpb2.start(1)
        root.after(1000, # in milliseconds
                   lambda *e: self.connect())   
        root.mainloop()
        ...
    def connect(self):
        print "querying"
        self.cursor = SolvittConnect(<SQL>)
        print "query complete"

Note that your SolvittConnect will probably stop the GUI from updating- look into throwing that to a thread or a worker pool, since the GUI can't update while python is executing a function (unless there are explicit calls during execution, but SolvittConnect doesn't explicitly tell the GUI to update while it tries to connect) 请注意,您的SolvittConnect可能会阻止GUI更新-将其扔到线程或工作池中,因为在python执行函数时GUI无法更新(除非在执行过程中有明确的调用,但SolvittConnect不会) t明确告诉GUI在尝试连接时进行更新)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM