首页 > 解决方案 > AttributeError:'str'对象在python pyQt中没有属性'set'错误

问题描述

我有这个代码:

self.entriesx = self.generate_stringvars()

# Fill in the entry fields if a template is selected.
def autofill(self):
    # Generate a dictionary of all the saved templates.
    test_dictionary = self.build_test_dictionary()
    # Retrive the selected qual name from the form.
    self.coded_entry = self.comboBox.currentText()
    entries = test_dictionary[self.coded_entry]
    # Set each entry field in self.entriesx to the corresponding value
    # from the template.
    i_count = 0
    for i in self.entriesx:
        i.set(entries[i_count])
        i_count += 1
    # Reload the entry fields with their new values.
    self.add_entry_fields()

autofill(self)函数根据从组合框中选择的项目自动将相应的条目填充到输入字段中。自动填充功能也依赖于这个功能:

# Generate a list of string variables to store the entries.
def generate_stringvars(self):
    temp_entriesx = []
    count = 0
    while count < 21:
        temp_entriesx.append("")
        count += 1
    return temp_entriesx

当我编译我的代码时,我得到一个错误AttributeError: 'str' object has no attribute 'set' for i.set(entries[i_count])在我的自动填充函数中。我如何解决它?

编辑:这是这篇文章 的后续问题。

标签: pythonpyqt

解决方案


对于困惑的人,这是对这个问题的跟进。OP 正在尝试从 Tkinter 移植到 pyQt。

Tkinter 的StringVar接口与 python 不同str。赋值是使用赋值运算符 ( =) 完成的。此外,作为一般规则,尽量不要i对非整数类型使用或类似。这没有错,只是糟糕的编码习惯。此外,因为您不再需要元素本身。只需使用range.

for i in range(len(self.entriesx)):
    self.entriesx[i] = entries[i]

推荐阅读