gpt4 book ai didi

Python 对象没有属性

转载 作者:行者123 更新时间:2023-12-01 07:18:25 24 4
gpt4 key购买 nike

我有一个奇怪的问题。
我有一个可以运行的测试脚本。现在我在我的主脚本中使用了相同的代码,现在它不起作用,我不知道为什么不这样做。
所以我希望有人能看看出了什么问题。

当我运行脚本时,我会抛出一个错误:

File "E:/Python/Amp_Glade_1.py", line 226, in
on_volume_scale_value_changed
self.update_control("volume", x)
File "E:/Python/Amp_Glade_1.py", line 264, in update_control
self.control[self.name] = self.value
AttributeError: 'GTK_Main' object has no attribute 'control'

所以在:
def on_volume_scale_value_changed(self, object, data=None):
x = int(self.volume.get_value())
y = self.volume_step[x]
self.label_volume.set_text(str(y))
self.update_control("volume", x)

我打电话:
def update_control(self, name, value):
self.name = name
self.value = value
self.control[self.name] = self.value

而且我看不到会导致该错误的原因,因为它正在我的测试脚本中工作。
这是 self.control 的字典:
self.control = {"volume": 3, "bass": 0,
"middle": 0, "treble": 0,
"center": 16, "pre_gain": 0}

这是脚本:
#!/usr/bin/env python
'''
GUI / Amlifier control
Connects to ESP8266 on wifi
Controls Pre-Amp and Amplifier

'''
try:
import os
except:
print ("No os")

try:
import thread
except:
print ("No thread")

try:
import gi
except:
print ("No gi")

try:
import sys
except:
print ("No sys")

try:
gi.require_version('Gtk', '3.0')
from gi.repository import GObject, Gtk as Gtk
except:
print ("No Gtk")

try:
import socket
except:
print ("No socket")

try:
from datetime import datetime, timedelta
except:
print ("No datetime, timedelta")

try:
# neede for window.get_xid(), xvimagesink.set_window_handle(), respectively:
gi.require_version('GdkX11', '3.0')
from gi.repository import GdkX11
except:
print ("No GdkX11")
sys.exit()


class GTK_Main(object):

def __init__(self, sock=None):

## Create window
self.gladefile = ("Amp_2.glade")
self.builder = Gtk.Builder()
self.builder.add_from_file(self.gladefile)
self.builder.connect_signals(self)

## Create objects by name frpm gladefile
self.window = self.builder.get_object("window")
self.Store = self.builder.get_object("Store")
self.Mute = self.builder.get_object("Mute")
self.Load = self.builder.get_object("Load")
self.Reset = self.builder.get_object("Reset")
self.bass = self.builder.get_object("bass_scale")
self.middle = self.builder.get_object("middle_scale")
self.treble = self.builder.get_object("treble_scale")
self.volume = self.builder.get_object("volume_scale")
self.pre_gain = self.builder.get_object("gain")
self.center = self.builder.get_object("center_scale")
self.label_bass = self.builder.get_object("label_bass")
self.label_middle = self.builder.get_object("label_middle")
self.label_treble = self.builder.get_object("label_treble")
self.label_volume = self.builder.get_object("label_volume")
self.label_pre_gain = self.builder.get_object("label_gain")
self.label_center = self.builder.get_object("label_center")
self.label_IP = self.builder.get_object("label_IP")
self.label_Port = self.builder.get_object("label_Port")
self.label_connected = self.builder.get_object("label_connected")
self.image_mute = self.builder.get_object("image1")
self.image_radio_1 = self.builder.get_object("image2")
self.image_radio_2 = self.builder.get_object("image3")
self.image_radio_3 = self.builder.get_object("image4")
self.image_radio_4 = self.builder.get_object("image5")
self.radiobutten_1 = self.builder.get_object("radiobutton1")
self.radiobutten_2 = self.builder.get_object("radiobutton2")
self.radiobutten_3 = self.builder.get_object("radiobutton3")
self.radiobutten_4 = self.builder.get_object("radiobutton4")

self.window.show_all()

## Set init values
self.mute_state = False
self.center.set_value(16)

self.host = '192.168.0.23'
self.port = 8888

## Create TCP socket
if sock is None:
self.sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
else:
self.sock = sock

self.connect(self.host, self.port)

## Scale steps
self.volume_step = (-40, -32. -24, -16, -8, -7,
-6, -5, -4, -3, -2, -1, 0)

self.pre_gain_step = (0, 2, 4, 6, 8, 10, 12, 14,
16, 18, 20, 22, 24, 26, 28, 30)

self.bass_step = (-14, -12, -10, -8, -6, -4, -2, 0,
2, 4, 6, 8, 10, 12, 14)

self.middle_step = (-14, -12, -10, -8, -6, -4, -2, 0,
2, 4, 6, 8, 10, 12, 14)

self.treble = (-14, -12, -10, -8, -6, -4, -2, 0,
2, 4, 6, 8, 10, 12, 14)

self.right_step = (0, -1, -2, -3, -4, -5, -6,
-7, -8, -16, -24, -32,
-40, -48, -56, -64, -72)

self.left_step = (0, -1, -2, -3, -4, -5, -6,
-7, -8, -16, -24, -32,
-40, -48, -56, -64, -72)

## Set init scale values
self.volume.set_value(3)

## JSON
self.control = {"volume": 3, "bass": 0,
"middle": 0, "treble": 0,
"center": 16, "pre_gain": 0}

## Graphic elements to control
self.GUI_labels = {"volume": self.label_volume,
"bass": self.label_bass,
"middle": self.label_middle,
"treble": self.label_treble,
"center": self.label_center,
"pre_gain": self.label_pre_gain}

self.GUI_items = {"volume": self.volume, "bass": self.bass,
"middle": self.middle, "treble": self.treble,
"center": self.center, "pre_gain": self.pre_gain}

## start ping to server
thread.start_new_thread(self.ping_send(), )

## Create handles
def on_window_destroy(self, obkect, data=None):
self.sock.close()
thread.exit()
Gtk.main_quit()

def connect(self, host, port):
try:
self.sock.connect((self.host, self.port))
self.label_connected.set_text("Connection:")
self.label_IP.set_text(self.host)
self.label_Port.set_text(str(self.port))
except Exception as e:
print("No connection. Exceptions is %s:" % (e))
self.label_connected.set_text("No connection")

return None

def on_Mute_released(self, object, data=None):
if not self.mute_state:
self.image_mute.set_from_file("circle_red_small.png")
self.mute_state = True
else:
self.image_mute.set_from_file("circle_blue_small.png")
self.mute_state = False

def on_radiobutton1_pressed(self, object, data=None):
self.image_radio_1.set_from_file("circle_green_small.png")
self.image_radio_2.set_from_file("circle_blue_small.png")
self.image_radio_3.set_from_file("circle_blue_small.png")
self.image_radio_4.set_from_file("circle_blue_small.png")

def on_radiobutton2_pressed(self, object, data=None):
self.image_radio_2.set_from_file("circle_green_small.png")
self.image_radio_1.set_from_file("circle_blue_small.png")
self.image_radio_3.set_from_file("circle_blue_small.png")
self.image_radio_4.set_from_file("circle_blue_small.png")

def on_radiobutton3_pressed(self, object, data=None):
self.image_radio_3.set_from_file("circle_green_small.png")
self.image_radio_1.set_from_file("circle_blue_small.png")
self.image_radio_2.set_from_file("circle_blue_small.png")
self.image_radio_4.set_from_file("circle_blue_small.png")

def on_radiobutton4_pressed(self, object, data=None):
self.image_radio_4.set_from_file("circle_green_small.png")
self.image_radio_1.set_from_file("circle_blue_small.png")
self.image_radio_2.set_from_file("circle_blue_small.png")
self.image_radio_3.set_from_file("circle_blue_small.png")

def on_Reset_released(self, object, data=None):
pass

def on_Store_released(self, object, data=None):
pass

def on_Load_released(self, object, data=None):
pass

def on_center_scale_value_changed(self, object, data=None):
pass

def on_volume_scale_value_changed(self, object, data=None):
x = int(self.volume.get_value())
y = self.volume_step[x]
self.label_volume.set_text(str(y))
self.update_control("volume", x)

def on_bass_scale_value_changed(self, object, data=None):
pass

def on_middle_scale_value_changed(self, object, data=None):
pass

def on_treble_scale_value_changed(self, object, data=None):
pass

def on_gain_scale_value_changed(self, object, data=None):
pass

def ping_send(self):
now = datetime.now()
next_ping= now + timedelta(hours = 0, minutes = 0, seconds = 5)
while True:
if next_ping <= datetime.now():
self.mysend("OK")
now = next_ping
next_ping = datetime.now() + timedelta(hours = 0, minutes = 0,
seconds = 5)
while Gtk.events_pending():
Gtk.main_iteration()

def mysend(self, msg):
totalsent = 0
MSGLEN = len(msg)
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("Socket connection broken")
totalsent = totalsent + sent

def update_control(self, name, value):
self.name = name
self.value = value
self.control[self.name] = self.value

def write_json(self):
with open("amp.dat", "w+") as jsonFile:
jsonFile.write(json.dumps(self.control))
jsonFile.close()

def load_json(self):
with open("amp.dat", "r") as jsonFile:
data = json.load(jsonFile)
jsonFile.close()
self.control = json.dumps(data)

def update_GUI(self):
for key in self.control.items():
if key == "gain":
pass
else:
x = self.GUI_labels[key]
x.set_text(str(value))
y = self.GUI_items[key]
y.set_value(value)


GObject.threads_init()
GTK_Main()
Gtk.main()

所以也许有人可以告诉你怎么了?
我真的很感激。

最佳答案

这段代码有很多问题。我将首先说明我认为的问题以及如何解决该问题,然后再讨论其他问题。

这里有很多不明显的东西,我想这是因为 GTK 框架隐含地做了一些事情。例如,我注意到 GTK_Main被实例化,但生成的对象永远不会保存在任何地方。我的猜测是当你这样做时会发生某种奇怪的嵌套依赖

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

并且不知何故 this 允许实例化对象与 GTK 事件循环连接。

我还怀疑 builder期望这个对象实现像 on_volume_scale_value_changed 这样的方法当音量刻度值改变时执行。

如果这是真的,那么下面的代码会导致错误

        ## Set init scale values
self.volume.set_value(3)

## JSON
self.control = {"volume": 3, "bass": 0,
"middle": 0, "treble": 0,
"center": 16, "pre_gain": 0}

这是因为设置音量会触发 on_volume_scale_value_changed被调用,试图访问 self.control ,但您没有定义 self.control直到音量设置完毕。颠倒顺序应该可以解决问题。

一般来说,你应该
  • 总是在执行任何逻辑(比如设置音量)之前设置数据成员(比如 self.control ,因为它只保存数据)和
  • 请注意事物的调用顺序,这样您就不会陷入这样的循环。


  • 话虽如此,您将遇到的下一个问题是:

        def load_json(self):
    with open("amp.dat", "r") as jsonFile:
    data = json.load(jsonFile)
    jsonFile.close()
    self.control = json.dumps(data)
    self.control应该是字典,但您将其设置为 json.dumps 的输出这将是一个字符串。因此,如果您调用该函数,您的代码将停止工作。你应该做 self.control = json.load(jsonFile) .

    此外,在上下文管理器( with block )中,文件在退出时自动关闭,因此调用 jsonFile.close()显式充其量是多余的 - 最坏的情况是它可能会在退出 with 时引发错误阻止,因为文件已经关闭。

    全部

    try:
    import sys
    except:
    print ("No sys")

    由于以下原因非常糟糕
  • 你在做毯子except ,而不是捕获特定错误。我假设您正在尝试捕捉 ImportError , 所以你应该做 except ImportError .您知道可能会引发哪些其他类型的异常,因此您不知道什么会被吞下并使您的系统处于无效状态。这让我想到了
  • 您正在尝试导入一个模块,但如果失败,您只是打印它不存在并继续前进。在 os 的情况下和 sys没关系,因为你从不使用 os (虽然我会说你应该避免导入你不使用的东西)和sys仅用于 sys.exit() (无论如何都会触发退出,因为 sys 丢失了),但是如果 datetime不能导入?您使用 datetime在您的代码中,因此当您尝试使用 datetime 时,您的代码可能会运行谁知道多长时间然后突然失败.一般来说,尽早并描述性地失败比让您的系统处于随时可能失败的损坏状态要好得多。
  • 您正在使用的大多数导入都来自标准库。如果缺少标准库中的某些内容,则存在问题。特别是 sys ...我认为没有 sys 就无法启动 python .
  • 如果模块不存在,它将引发 ImportError并告诉用户它不存在,然后停止代码。这就是您想要的,因为如果缺少 GTK,您将无法运行您的代码。

  • 道德:永远不要吞下错误并继续前进,因为它会使您的系统处于崩溃状态,任何时候事情都可能无缘无故地失败。

    关于Python 对象没有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57836346/

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