2

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!

Rob
  • 31
  • 3
  • It it is definitely something to do with the filedialog. If you comment out the filedialog you no longer have that problem. Why do you need the filedialog to open up at the start? – Mike - SMT Aug 21 '18 at 21:01
  • 1
    I'm guessing you're running on windows. Is that correct? If so, this is a known problem. You need to start the mainloop before displaying any dialogs. – Bryan Oakley Aug 21 '18 at 21:26
  • Good to know. I can switch it around. Thanks! – Rob Aug 22 '18 at 17:56

1 Answers1

1

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)
Mike - SMT
  • 14,784
  • 4
  • 35
  • 79