圖形使用者介面常見問答集

圖形使用者介面 (GUI) 的常見問題

Python 有哪些 GUI 套件?

Python 的標準版本會包含一個 Tcl/Tk 小工具集 (widget set) 的物件導向介面,稱為 tkinter。這可能是最容易安裝(因為它已包含在 Python 的大多數二進制發行版本中)和使用的。有關 Tk 的詳細資訊(包含指向原始碼的指標),請參閱 Tcl/Tk 首頁。Tcl/Tk 在 macOS、Windows 和 Unix 平台上是完全可攜 (portable) 的。

根據你要使用的平台,還有其他幾種選擇。在 python wiki 上可以找到一份跨平台的以及各平台專屬的 GUI 框架清單。

Tkinter 的問答

如何凍結 Tkinter 應用程式?

凍結 (freeze) 是一個能建立獨立應用程式的工具。在凍結 Tkinter 應用程式時,該應用程式不是真正的獨立,因為該應用程式仍然需要 Tcl 和 Tk 函式庫。

One solution is to ship the application with the Tcl and Tk libraries, and point to them at run-time using the TCL_LIBRARY and TK_LIBRARY environment variables.

要得到真正獨立的應用程式,必須將構成函式庫的 Tcl 腳本也整合到應用程式中。一個可支援該方法的工具是 SAM(stand-alone modules,獨立模組),它是 Tix 發行版的一部分 (https://tix.sourceforge.net/)。

請在 SAM 被啟用的情況下建置 Tix,對 Python 的 Modules/tkappinit.c 中的 Tclsam_init() 等函式執行適當的呼叫,並與 libtclsam 和 libtksam 連結(你可能也會 include Tix 函式庫)。

是否可以在等待 I/O 時處理 Tk 事件?

On platforms other than Windows, yes, and you don't even need threads! But you'll have to restructure your I/O code a bit. Tk has the equivalent of Xt's XtAddInput() call, which allows you to register a callback function which will be called from the Tk mainloop when I/O is possible on a file descriptor. See File Handlers.

我無法讓鍵繫結 (key binding) 在 Tkinter 中作用:為什麼?

An often-heard complaint is that event handlers bound to events with the bind() method don't get handled even when the appropriate key is pressed.

最常見的原因是,繫結到的小工具並沒有「鍵盤焦點 (keyboard focus)」。請查看 Tk 說明文件中關於焦點命令的敘述。通常,點擊一個小工具,會讓它得到鍵盤焦點(但不適用於標籤;請參閱 takefocus 選項)。