1

Can you block the user from using spaces in an entry box in tkinter?

Its for creating a filename, so if they put spaces it won't work.

hastur
  • 13
  • 5
  • what did you try? Where is your code? You may `bind()` function to `Entry` which will check every `key` and delete space in entry when user press space. OR you should simply check `if " " in filename:...message...` after getting filename to display warning and wait for correction. – furas Aug 18 '22 at 12:53
  • See [Interactively validating Entry widget content in tkinter](https://stackoverflow.com/questions/4140437/interactively-validating-entry-widget-content-in-tkinter/4140988#4140988). Though, I think all modern operating systems allow spaces in filenames so you might be needlessly limiting the user to what they can use. – Bryan Oakley Aug 18 '22 at 17:39

1 Answers1

1

You can use either this to prevent the user:

if no_spaces.count(' ') > 0:
    print("Please try again")

or the function strip. Python String strip() function will remove leading and trailing whitespaces, so if the user type "my file name.txt" your file will be myfilename.txt

You can also replace the spaces by underscores:

mystring.replace(" ", "_")

Regards, Izabela.

Izalion
  • 708
  • 4
  • 11