Home > Mobile >  tkinter StringVar() AttributeError
tkinter StringVar() AttributeError

Time:11-19

I am developing a Tkinter app. In the StringVar() part, It gets an Error:

AttributeError: 'StringVar' object has no attribute 'tk'. Did you mean: '_tk'?

I've imported the module: import tkinter as tk

and here is the StringVar() part: (Error on line 2)

games = ["Select Game", "Number Memory", "Reaction", "Game"]
var = tk.StringVar()
var.set(games[0])
game_dropdown = tk.OptionMenu(var, *games)

For more information, Here is the full code and errors:

import tkinter as tk
root = tk.Tk()
root.title("Game Launcher")
root.iconbitmap("app.ico")
root.geometry("800x400")
root.resizable(False, False)
title = tk.Label(text="Game Laucher", font=("Arial", 24))
title.pack()
title.place(x=10, y=10)
games = ["Select Game", "Number Memory", "Reaction", "Game"]
var = tk.StringVar()
var.set(games[0])
game_dropdown = tk.OptionMenu(var, *games)
game_dropdown.pack()
game_dropdown.place(x=10, y=70)
root.mainloop()
PS D:\Test\Python\Game> py launcher.pyw
Traceback (most recent call last):
  File "D:\Test\Python\Game\launcher.pyw", line 13, in <module>
    game_dropdown = tk.OptionMenu(var, *games)
  File "C:\Users\???\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 3991, in __init__
    Widget.__init__(self, master, "menubutton", kw)
  File "C:\Users\???\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 2595, in __init__
    BaseWidget._setup(self, master, cnf)
  File "C:\Users\???\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 2564, in _setup
    self.tk = master.tk
AttributeError: 'StringVar' object has no attribute 'tk'. Did you mean: '_tk'?

CodePudding user response:

Thanks to John Gordon, I've found an answer:

The first argument to OptionMenu() should be the parent widget object

CodePudding user response:

The error means that the StringVar object is not a Tk instance.

The wrong part is in the line:

game_dropdown = tk.OptionMenu(var, *games)

The first attribute should be the parent of the object(which should be a Tk instance), not a StringVar.

You can change that line to:

game_dropdown = tk.OptionMenu(root, var, *games)
  • Related