PySimpleGUI / Tk:在 Mac 上启动非常慢

PySimpleGUI / Tk: very slow startup on Mac

我花了很多时间试图理解为什么在 Mac OS X 上使用 Tk 加载 PySimpleGUI 需要这么多时间。

更具体地说:

window.refresh()

9 秒 完成我的(非常简单)UI。我为了调查减少了它,所以现在需要 3 秒。

它发生 大约 1/7 的时间,而在其他时间通常很短。 Windows 上的相同应用未显示此问题。

减少后的UI是这样的:

布局是这样的:

Top (2)
--- Row ------->
------- Column ()
--------|--- Btn "Camera" | Btn "Close"
--------|--- 
--- Row ------->
------- Column (left-col)
--------| Row ------->
--------|--- Btn "4" | Btn "10" | Btn "20" | Btn "40" | 
--------|---- Column ()
--------|-----|--- CB "Scale Bar"
--------|-----|--- CB "White Bar"
--------| Row ------->
--------|--- Btn "BrFd" | Btn "DAPI" | Btn "FITC" | Btn "CY3"
--------| Row ------->
--------|--- Multiline | Btn ""
--------| Row ------->
--------|--- Multiline | Btn ""
--------| Row ------->
--------|--- Btn "" | Btn "Show Last" | Btn "Save" | Btn "Export IJ"
--------| Row ------->
--------|--- Btn "Export TIF" | Btn "Delete Checked"

我是 运行 它与分析器:

rm prof && python -m cProfile -o prof uscope.py

然后使用此代码:

import pstats
from pstats import SortKey
p = pstats.Stats('prof')
p.sort_stats(SortKey.CUMULATIVE).print_stats(10)

获取此分析:

Thu Apr 29 15:10:39 2021    prof

         204224 function calls (199897 primitive calls) in 4.099 seconds

   Ordered by: cumulative time
   List reduced from 2141 to 10 due to restriction 

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    552/1    0.003    0.000    4.100    4.100 {built-in method builtins.exec}
        1    0.000    0.000    4.100    4.100 uscope.py:24()
        1    0.000    0.000    3.460    3.460 /Users/u/Prog/c/pbio-printer/camera2/VerySimpleGUI2.py:335(build_and_run)
  393/389    3.170    0.008    3.170    0.008 {method 'call' of '_tkinter.tkapp' objects}
        1    0.000    0.000    2.978    2.978 /Users/u/opt/miniconda3/envs/camera/lib/python3.7/site-packages/PySimpleGUI/PySimpleGUI.py:8247(refresh)
        1    0.000    0.000    2.978    2.978 /Users/u/opt/miniconda3/envs/camera/lib/python3.7/tkinter/__init__.py:1175(update)
   278/10    0.002    0.000    0.638    0.064 :978(_find_and_load)
   277/10    0.001    0.000    0.638    0.064 :948(_find_and_load_unlocked)
   386/11    0.000    0.000    0.636    0.058 :211(_call_with_frames_removed)
    258/8    0.001    0.000    0.635    0.079 :663(_load_unlocked)

有问题的行似乎是这一行:

 393/389    3.170    0.008    3.170    0.008 {method 'call' of '_tkinter.tkapp' objects}

如果能提供有关此问题的任何线索,我将不胜感激!

我对此没有很好的解释,但感谢@lenka_cizkova 添加的评论,我现在可以提供一个解决方法:

通过添加启动画面,即使是很短的画面(100 毫秒),也会立即加载主屏幕:

# Splash screen to eliminate long loading time on Mac OSX
if os.name != 'nt':
    SPLASH_IMAGE_FILE = 'img/my-logo.png'
    DISPLAY_TIME_MILLISECONDS = 100
    sg.Window('',
              [[sg.Image(SPLASH_IMAGE_FILE)]], transparent_color=sg.theme_background_color(),
              no_titlebar=True, keep_on_top=True).read(timeout=DISPLAY_TIME_MILLISECONDS, close=True)

此代码应放在构建和显示主要内容之前 window。