Skip to main content
 首页 » 编程设计

python之无法在 ubuntu 16.04.2 上的 tkinter 中使用 tk.mainloop()

2024年10月01日7fff_TT

每当我尝试在 ubuntu 16.04.2 上使用 tk.mainloop() 运行一个简单的 tkinter 程序 - 或该 Material 的任何程序时,我无法打开应用程序窗口和一个问号显示在窗口图标上。

这是我正在运行的程序:

import tkinter as tk 
 
class MainApplication(tk.Frame): 
    def __init__(self, parent, *args, **kwargs): 
        super(MainApplication, self).__init__(parent, *args, **kwargs) 
 
if __name__ == '__main__': 
    root = tk.Tk() 
    MainApplication(root).pack(side="top", fill="both", expand=True) 
    root.mainloop() 

这是一个屏幕截图,显示了我每次运行该程序时的输出:

在此之前,我收到一条错误消息,指出可以加载 _tkinter。为了解决这个问题,我使用 sudo apt-get update 为 ubuntu 下载了最新版本的 tkinter,然后使用 sudo apt-get install python3-tk。如果这也很重要,我将在 Windows 10 的双启动配置中使用 ubuntu。

我也读过 How can I fix program icons that appear as a question mark in the Launcher?和 Why do some open applications appear as “question marks” in the Unity launcher? ,但这些问题似乎是在处理如何修复应用程序桌面图标,而不是如何修复无法运行的应用程序。此外,这个问题似乎是在处理特定的 ubuntu 应用程序。

有谁知道为什么 ubuntu 不能正确运行 tkinter 应用程序以及如何解决这个问题?

请您参考如下方法:

虽然我看起来不像,但 tkinter 窗口实际上在那里。它很小很容易看到,因为它里面没有小部件来扩展它。一旦您开始向窗口添加小部件,它就会变得可见。

例如,要使用相关代码显示一个窗口,

import tkinter as tk 
 
 
class MainApplication(tk.Frame): 
    def __init__(self, parent, *args, **kwargs): 
        super(MainApplication, self).__init__(parent, *args, **kwargs) 
 
 
if __name__ == '__main__': 
    root = tk.Tk() 
    MainApplication(root).pack(side="top", fill="both", expand=True) 
    root.mainloop()  

您可以添加一个 tk.Button() 小部件来强制展开窗口:

import tkinter as tk 
 
 
class MainApplication(tk.Frame): 
    def __init__(self, parent, *args, **kwargs): 
        super(MainApplication, self).__init__(parent, *args, **kwargs) 
        # create a button widget to force the window to expand to fit 
        # the button 
        self.btn = tk.Button(self, text='btn', bg='blue') 
        self.btn.pack(side='bottom') 
 
 
if __name__ == '__main__': 
    root = tk.Tk() 
    MainApplication(root).pack(side="top", fill="both", expand=True) 
    root.mainloop() 

显示以下窗口: