gpt4 book ai didi

python - 如何使用 Gtk.events_pending?

转载 作者:太空宇宙 更新时间:2023-11-04 04:32:28 25 4
gpt4 key购买 nike

我有这个基本的“测试”应用程序,我想在其中显示一个微调器,同时它正在执行其漫长的启动过程(具有数据库请求的功能)让用户知道它不是窃听而是启动。我在其他帖子中读到可以使用 Gtk.events_pending() 函数执行此操作,但我不知道如何/在何处使用它。我尝试了很多方法,但主窗口总是仅在请求完成时显示:

这是主要的 .py 文件:

#!/usr/bin/python3
# -*- coding: Utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GdkPixbuf, GObject

import Mng,os.path

path = os.path.dirname(os.path.realpath(__file__))

# MAIN WINDOW ######################################################################################
class PyApp:
def __init__(self):
builder = Gtk.Builder()
builder.add_from_file(path + "/test.glade")
self.obj = builder.get_object

"""
I would like to display on main window a
spinner while doing requests. There is a
self.obj('spinner') in main window,
in glade file to do so.
"""
self.do_requests()

self.obj('main').show_all()

def do_requests(self):
mng = Mng.Grab([
[1,'getPlayers'],
[2,'getFactions'],
[3,'getBoards']
])
data = mng.grab_data()
players, nb = data[1]
factions, nb = data[2]
boards, nb = data[3]

"""
Here will be the code to display data in GUI,
like for example : self.obj('label_players').set_text(str(players))
"""

if __name__ == "__main__":
app = PyApp()
Gtk.main()

这是 Mng.py 文件,我将在其中管理我在一个类中的所有请求(我不知道它是否编码良好,因为我刚刚发现多线程。但它确实有效):

#!/usr/bin/python3
# -*- coding: Utf-8 -*-
import os.path, DB
import concurrent.futures

path = os.path.dirname(os.path.realpath(__file__))


class Grab:
"""
Retrieves multiple database requests datas
& returns results in a dict : {name of request: [result, lenght of result]}
"""
def __init__(self, req_list):
self.req_list = req_list

def grab_data(self):

def do_req(var, funct_name, args):
if None in args:
funct = getattr(self, str(funct_name))()
else:
#print("function",name,"*args : ", *args)
funct = getattr(self, str(funct_name))(*args)
res = [var, funct]
return res

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
res_list = {}
future_to_req = {executor.submit(do_req, req[0], req[1], req[2:]): req for req in self.req_list}
for future in concurrent.futures.as_completed(future_to_req):
req = future_to_req[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (req, exc))
else:
res_list[data[0]] = data[1]

return res_list

def getFactions(self, ext1=False):
req = DB.DB('SELECT * FROM factions')
res = req.res
nb = len(res)
return res, nb

def getBoards(self, ext1=False):
req = DB.DB('SELECT * FROM boards')
res = req.res
nb = len(res)
return res, nb


def getPlayers(self):
req = DB.DB('SELECT * FROM players')
res = req.res
nb = len(res)
return res, nb

DB.py 文件执行请求:

#!/usr/bin/python3
# -*- coding: Utf-8 -*-

import mysql.connector as sql

class DB(object):
"""DB initializes and manipulates MySQL databases."""

def __init__(self, query):
"""Initialize a new or connect to an existing database.
Accept setup statements to be executed.
"""
self.database = '******'
self.host = '**********'
self.port = '********'
self.user = '******'
self.password = '***********'
self.connect()
self.execute(query)
self.close()

def connect(self):
"""Connect to the MySQL database."""

self.connection = sql.connect(host=self.host,port=self.port,user=self.user,password=self.password, database=self.database)
self.cursor = self.connection.cursor()
self.connected = True

def close(self):
"""Close the MySQL database."""

self.connection.close()
self.connected = False

def execute(self, query):
"""Execute complete SQL statements. """
res = close = False
if not self.connected:
self.connect()
close = True

try:
self.cursor.execute(query)
if query.upper().startswith('SELECT'):
res = self.cursor.fetchall()

except sql.Error as e:
try:
print ("MySQL Error [%d]: %s" % (e.args[0], e.args[1]))
except IndexError:
print ("MySQL Error: %s" % str(e))

if close:
self.close()

self.res = res

你能告诉我怎么做吗?

最佳答案

这可能有助于您了解多处理的工作原理。抱歉,我无法为您提供内置代码的完整演示,但希望您能理解。

#!/usr/bin/env python3

from gi.repository import Gtk, GLib, Gdk
from multiprocessing import Queue, Process
from queue import Empty
import os, sys, time

UI_FILE = "src/pygtk_foobar.ui"

class GUI:
def __init__(self):

self.builder = Gtk.Builder()
self.builder.add_from_file(UI_FILE)
self.builder.connect_signals(self)

self.window1 = self.builder.get_object('window1')
self.window1.show_all()
self.builder.get_object('spin1').start()

self.data_queue = Queue()
thread = Process(target=self.thread_start)
thread.start()

GLib.timeout_add(100, self.get_result )

def thread_start (self):
time.sleep(5)
self.data_queue.put("done")

def get_result (self):
try:
result = self.data_queue.get_nowait()
print (result)
self.builder.get_object('spin1').stop()
except Empty:
return True

def on_window_destroy(self, window):
Gtk.main_quit()

def main():
app = GUI()
Gtk.main()

if __name__ == "__main__":
sys.exit(main())

编辑

解释:只要 get result 返回 True,GLib.timeout_add() 就会继续轮询。当超时返回 None 或 False 时,它​​将退出轮询。 get result 将尝试从 data_queue 中获取结果,但如果没有找到,它将返回 True。

在您的情况下,您将使用 def thread_start 打开数据库请求并使用 def get_result 检查队列,直到信息被加载。所以 multiprocessing 将在一个线程中加载 db 信息,而 Gtk 可以在另一个线程中绘制其窗口,同时定期检查 multiprocessing db 线程是否完成。当它完成加载时,通过不返回 True 来取消超时,然后用数据库数据做你的事情。

例如,我经常使用它来填充扫描仪,而用户可以操作 GUI。

希望这对您有所帮助。

关于python - 如何使用 Gtk.events_pending?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52420899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com