Skip to main content
 首页 » 编程设计

python之将作为对象的默认参数添加到类内部的函数

2025年04月02日9cloudgamer

我正在尝试为 linux 中的 mate-panel 制作一个小程序。我必须要模块 Window.py 和 Applet.py。我收到此错误:

Traceback (most recent call last): 
File "./Applet.py", line 37, in WindowButtonsAppletFactory 
WindowButtonsApplet(applet) 
File "./Applet.py", line 23, in WindowButtonsApplet 
CloseButton.connect("Clicked",WindowActions().win_close(SelectedWindow)) 
File "WindowButtonsApplet/Window.py", line 23, in win_close 
Window.close(Timestamp) 
AttributeError: 'WindowActions' object has no attribute 'close' 
 
** (Applet.py:2191): WARNING **: need to free the control here 

我不知道为什么 wnck librally 有一个名为 close 的属性。 我不想问的第二件事是为什么每次调用它时都需要初始化类。

代码来自: 小程序.py

#!/bin/env python3 
 
import gi 
import Window 
 
gi.require_version("Gtk","3.0") 
gi.require_version("MatePanelApplet", "4.0") 
 
from gi.repository import Gtk 
from gi.repository import MatePanelApplet 
from Window import * 
 
 
def WindowButtonsApplet(applet): 
 
    Box = Gtk.Box("Horizontal") 
 
    CloseButton = Gtk.Button("x") 
    MinButton = Gtk.Button("_") 
    UmaximizeButton = Gtk.Button("[]") 
 
    SelectedWindow = WindowActions().active_window() 
    CloseButton.connect("Clicked",WindowActions().win_close(SelectedWindow)) 
    Box.pack_start(CloseButton) 
 
    applet.add(Box) 
    applet.show_all() 
 
// Hack for transparent background 
 
applet.set_background_widget(applet) 
 
def WindowButtonsAppletFactory(applet, iid,data): 
    if iid != "WindowButtonsApplet": 
        return False 
 
    WindowButtonsApplet(applet) 
 
    return True 
 
 //Mate panel procedure to load the applet on panel 
 
 MatePanelApplet.Applet.factory_main("WindowButtonsAppletFactory", True, 
                                    MatePanelApplet.Applet.__gtype__, 
                                    WindowButtonsAppletFactory, None) 

窗口.py

#!/usr/bin/env python3 
 
import time 
import gi 
 
gi.require_version("Gtk","3.0") 
gi.require_version("Wnck","3.0") 
 
from gi.repository import Gtk 
from gi.repository import Wnck 
 
class WindowActions: 
 
DefaultScreen = Wnck.Screen.get_default() 
DTimestamp = int(time.time()) 
 
def active_window(self,Screen=DefaultScreen):  
    Screen.force_update() 
    self.ActiveWindow = Screen.get_active_window() 
    return self.ActiveWindow 
 
def win_close(Window,Timestamp=DTimestamp): 
    Window.close(Timestamp) 
 
def win_minimize(self,Window): 
    Window.minimize() 
 
def win_umaximize(self,Window): 
    self.Window.maximize() 

请您参考如下方法:

您缺少对 self 的引用:

def win_close(Window,Timestamp=DTimestamp): 
    Window.close(Timestamp) 

因此传递了一个未定义关闭方法的 WindowActions 实例,并将您实际选择的窗口传递给 Timestamp。

将 self 添加到您的方法定义中,应该可以解决问题。