【问题标题】:Dont know how to solve error : AttributeError: 'str' object has no attribute 'set'不知道如何解决错误:AttributeError: 'str' object has no attribute 'set'
【发布时间】:2019-04-24 08:50:50
【问题描述】:

我试图在单击 OptionMenu 时获取结果。但是我不断收到错误消息。

>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\samue\AppData\Local\Programs\Thonny\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:\Users\samue\AppData\Local\Programs\Thonny\lib\tkinter\__init__.py", line 3440, in __call__
    self.__var.set(self.__value)
AttributeError: 'str' object has no attribute 'set'

我不知道如何解决这个问题,因为我希望能够找到用户选择的值,以便可以在另一个函数中使用它。

如果有帮助的话,数据库中存储的单词是城市名称。

def destination_selected() :
    selection = destination_choice.get()
    print(selection)

def destination_dropdownbox_GUI():
    destination = []
    cursor.execute('SELECT DISTINCT Destination FROM FlightTable ')
    row = str(cursor.fetchone())
    x = 0
    for x in row :
        row = str(cursor.fetchone())
        row = re.sub(r'\W+', '', row)
        destination.append(row)
        if row == 'None' :
            break
    destination.pop()
    print(destination)
    temp_dest = []
    temp_dest = destination
    print(temp_dest)
    destination_dropdownbox = OptionMenu(window, *temp_dest,command = destination_selected).pack()

我希望输出一个城市名称。例如'Oslo'

【问题讨论】:

  • 您有任何名为“无”的目的地吗?为什么将行与“无”而不是None 进行比较?
  • 我在您提供的代码中没有看到对.set 的任何引用。请编辑您的问题以包含完整的回溯(以 Traceback (most recent call last): 开头并以错误消息结尾的位)。
  • 错误告诉你到底出了什么问题:你在字符串上调用 set 方法,而字符串没有 set 方法。你为什么在字符串上调用set?此外,您发布的任何代码都不会导致此错误。请提供正确的minimal reproducible example
  • 这是我在 Tkinter 回调 Traceback 中运行代码异常时给出的完整错误(最近一次调用最后一次):文件“C:\Users\samue\AppData\Local\Programs\Thonny\lib\ tkinter_init_.py",第 1705 行,在 call 中返回 self.func(*args) 文件“C:\Users\samue\AppData\Local\Programs\Thonny\ lib\tkinter_init_.py",第 3440 行,在 call self.__var.set(self.__value) AttributeError: 'str' object has no attribute 'set' - @BoarGules
  • @BryanOakley 如果我没有将 cursor.fetchone() 分配为 str(),代码将无法工作,因为小部件在没有 OptionMenu 的情况下出现空白。

标签: python sql tkinter pyodbc


【解决方案1】:

如果您查看OptionMenu 小部件的文档,您会发现在master 参数之后必须提供variable。此参数必须设置为特殊 tkinter 变量之一(StringVar 等)。

你没有在这个参数位置给它一个适当的变量,所以 tkinter 使用你给它的字符串作为变量。当您更改值时,tkinter 将调用 set 方法。但是,由于您传递的是字符串而不是变量,因此您会收到 str 没有名为 set 的方法的错误。

解决方案是给OptionMenu 一个变量。我猜你已经定义了这个变量,因为你的destination_selected 方法调用了destination_choice.get()

假设destination_choice 是一个特殊的tkinter 变量,你需要像这样定义你的OptionMenu

OptionMenu(window, destination_choice, *temp_dest,command = destination_selected).pack()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-22
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 2021-04-06
    • 2022-12-04
    • 2022-11-11
    相关资源
    最近更新 更多