Tkinter - AttributeError:'str'对象没有属性'set'

时间:2015-08-05 21:40:23

标签: python string tkinter set optionmenu

这是我创建的代码并且正在尝试运行:

import tkinter as tk


def ok(val):
    print("Value is: ", val)

def say_hi(self):
    print("hi there, everyone!")

class Application(tk.Frame):

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        master.title("Hi There")
        master.geometry("400x400")
        self.createWidgets(master)

    def createWidgets(self, master=None):
        var = str()

        self.select = tk.OptionMenu(master, var, "one", "two","three", command=ok).grid(column=1, row=1)

        self.QUIT = tk.Button(master, text="QUIT", fg="red", command=root.destroy).grid(column=2, row=1)
        print ("HI")

root = tk.Tk()
app = Application(master=root)
app.mainloop()

但我收到以下错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
    return self.func(*args)
  File "C:\Python34\lib\tkinter\__init__.py", line 3308, in __call__
    self.__var.set(self.__value)
AttributeError: 'str' object has no attribute 'set'

我尝试搞乱一些变量并使用不同的方法让菜单工作,但似乎没有任何东西摆脱错误。

有关如何修复错误的想法吗?

1 个答案:

答案 0 :(得分:6)

使用StringVar而不是str

  def createWidgets(self, master=None):
        var = tk.StringVar()

python str没有set方法或属性,StringVar特定于tkinter以及您打算使用的内容。