es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

La función tkinter StringVar() está generando AttributeError.

Estoy desarrollando una aplicación Tkinter. En la parte StringVar (), ocurre un error:

AttributeError: el objeto ‘StringVar’ no tiene el atributo ‘tk’. ¿Querías decir ‘_tk’?

He importado el módulo: import tkinter como tk

y aquí está la parte StringVar (): (Error en la línea 2)
py
games = [“Seleccionar Juego”, “Memoria de Números”, “Reacción”, “Juego”]
var = tk.StringVar()
var.set(games[0])
game_dropdown = tk.OptionMenu(var, *games)

Para obtener más información, aquí está el código completo y los errores:

py
import tkinter como tk
root = tk.Tk()
root.title(“Lanzador de Juegos”)
root.iconbitmap(“app.ico”)
root.geometry(“800×400″)
root.resizable(False, False)
title = tk.Label(text=”Lanzador de Juegos”, font=(“Arial”, 24))
title.pack()
title.place(x=10, y=10)
games = [“Seleccionar Juego”, “Memoria de Números”, “Reacción”, “Juego”]
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
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: el objeto ‘StringVar’ no tiene el atributo ‘tk’. ¿Querías decir ‘_tk’?

Tags:  , ,

Answer

  1. Avatar for davy.ai

    Parece que estás intentando usar el objeto StringVar() como el maestro del widget OptionMenu(). Sin embargo, StringVar() no tiene un atributo tk, que se requiere para el widget OptionMenu().

    En su lugar, debes usar el objeto root como el maestro del widget OptionMenu().
    El código debe verse así:

    import tkinter como tk
    root = tk.Tk ()
    root.title ("Lanzador de juegos")
    root.iconbitmap ("app.ico")
    root.geometry ("800x400")
    root.resizable (Falso, Falso)
    title = tk.Label (text = "Lanzador de juegos", fuente = ("Arial", 24))
    title.pack ()
    title.place (x = 10, y = 10)
    juegos = ["Seleccionar juego", "Memoria numérica", "Reacción", "Juego"]
    var = tk.StringVar ()
    var.set (juegos [0])
    game_dropdown = tk.OptionMenu (root, var, * juegos)
    game_dropdown.pack ()
    game_dropdown.place (x = 10, y = 70)
    root.mainloop ()
    

Comments are closed.