Rob
Rob

Reputation: 31

python3 tkinter Entry() cannot select text field until I click outside app window once

I've written a very simple app with python3, tkinter, but am seeing some strange behaviour with Entry(). I'm new to tkinter and python.

import os
from tkinter import Tk, Entry, filedialog

class MyGUI:
    def __init__(self,master):

        self.master = master

        self.date_entry = Entry(master)
        self.date_entry.pack()
        self.date_entry.insert(0,"test")

        self.master.mainloop()

root = Tk()
root.directory = os.path.abspath(filedialog.askdirectory())
my_gui = MyGUI(root)

When I run this code, the second to last line is what is causing the following problem: When I try to edit the "test" text I cannot select it (no cursor or anything). However, if I click once away from the app (e.g. desktop) I can then edit it.

Does anyone know what the problem could be?

I was wondering if it's to do with a new app window being created by the filedialog, but I couldn't find an answer.

Thanks for your replies!

Upvotes: 2

Views: 1059

Answers (1)

Mike - SMT
Mike - SMT

Reputation: 15236

After testing this odd behavior a bit it appear as though as long as you add a button to get the directory the issue goes away.

I find it odd however and I will see if I can find anything that could explain why tkinter is acting like this.

This code should work for you:

import tkinter as tk
from tkinter import filedialog

class MyGUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        self.date_entry = tk.Entry(self)
        self.date_entry.pack()
        self.date_entry.insert(0, "test")
        self.directory = ""
        tk.Button(self, text="Get Directory", command=self.get_directory).pack()

    def get_directory(self):
        self.directory = filedialog.askdirectory()

MyGUI().mainloop()

UPDATE:

I have recently learned that adding update_idletasks() before the filedialog will fix the focus issue.

Updated code:

import os
from tkinter import Tk, Entry, filedialog

class MyGUI:
    def __init__(self,master):

        self.master = master

        self.date_entry = Entry(master)
        self.date_entry.pack()
        self.date_entry.insert(0,"test")

        self.master.mainloop()

root = Tk()
root.update_idletasks() # fix focus issue.
root.directory = os.path.abspath(filedialog.askdirectory())
my_gui = MyGUI(root)

Upvotes: 1

Related Questions