-1

I am trying to set focus on an entry window however I get an error throw every time.

AttributeError: 'NoneType' object has no attribute 'focus_set'

I looked up some examples of this and none of the suggestions worked. I'm assuming I have an error from naming something in my code if the function is just flat out not working.

Here is my code...

import tkinter as tk
from tkinter import ttk


def greet():
    print(f"Hello, {user_name.get() or 'World'}!")


root = tk.Tk()

user_name = tk.StringVar()

name_label = ttk.Label(root, text="Name: ").pack(side="left", padx=(0, 10))
name_entry = ttk.Entry(root, width=15, textvariable=user_name).pack(side="left")

name_entry.focus_set()

greet_button = ttk.Button(root, text="greet", command=greet).pack(side="left")

quit_button = ttk.Button(root, text="quit", command=root.destroy).pack(side="right")

root.mainloop()

I am normally develop we applications in JavaScript so python is a little unfamiliar to me, I am just trying to learn something new. Thanks!

Devin Bowen
  • 127
  • 1
  • 1
  • 13

1 Answers1

0

I found the answer but I don't know why it works. If i put pack on another line it works...

name_label = ttk.Label(root, text="Name: ").pack(side="left", padx=(0, 10))
name_entry = ttk.Entry(root, width=15, textvariable=user_name)
name_entry.pack(side="left")
name_entry.focus()
Devin Bowen
  • 127
  • 1
  • 1
  • 13
  • 1
    This works because the geometry manager methods `pack`, `place`, and `grid` all return `None`. So if you use `name_entry = ttk.Entry(...).pack()`, `name_entry` evaluates to `None`, but if you put `pack` on a separate line then `name_entry` will evaluate to the instance of `ttk.Entry` which is what you actually want. – JRiggles Jun 26 '23 at 15:19