Strawpick Gaming
Strawpick Gaming

Reputation: 17

How to set default value of an entry on tkinter?

I'm trying to make a form and its something like this

from tkinter import *
root = tk.Tk()
root.title("Form")

name = Label(root, text="Name", width=20,bg = "black", fg="red")
name.place(x=150, y=50)

name = Entry(root, width=20, bg = "black", fg="red")
name.place(x=150, y=100)

print(name.get)

and lets say someone leaves the "name" blank i want my code to detect that and print "unknown" instead of nothing

tip: i dont want the entry to have a text in it with already wrote unknown i want to be able to leave it blank and my print still be able to print unknown.

problem with the float:

def submit():
    kilograms = entry_kilo.get()
    kilo_float = float(kilograms)

Upvotes: 1

Views: 301

Answers (1)

Delrius Euphoria
Delrius Euphoria

Reputation: 15088

Here is a class I made so that it supports this type of activity.

from tkinter import *

class Custom(Entry): #inheriting from the Entry class
    def ret(self):
        if self.get() == '': # if empty then assign
            return 'Unknown'
        else:
            return self.get() # else give the same thing out

root = Tk()
root.title("Form")

name = Label(root, text="Name", width=20,bg = "black", fg="red")
name.place(x=150, y=50)

a = Custom(root, width=20, bg = "black", fg="red") #instantiating using all the same option you did before
a.place(x=150, y=100)

print(a.ret()) #Prints unknown
print(a.ret() == a.get()) #prints false obviously, just a testimony ;)

root.mainloop()

Here you have to use a.ret(), why? because thats how i defined it inside of the class. You could use a.get(), but it will just give you the usual blank string. And I dont think its possible to overwrite the existing get() method other than editing the __init__.py file of tkinter, do let me know if i'm wrong.

You can also shorten the class to just a little over multiple lines, like:

class Custom(Entry):
    def ret(self):
        return 'Unknown' if self.get() == '' else self.get() #does the same thing as before

Keep in mind, you can replace 'Unknown' with anything you like.

This is not the best of codes, as I have not used classes before. Why use classes? Because its not something thats possible with the default tkinter, i believe. So why not just make a custom class and get this effect ;)

How are you supposed to use this with your project? Just replace all the Entry(..) with Custom(..). It supports all the options that a usual Entry widget does too.

Make the changes here to fix the error:

def click():
    kilograms = a.ret()
    kilo_float = a.ret()
    try:
        kilo_float = float(kilograms)
    except ValueError:
        pass
    print(kilo_float)

Hope this helps you. Do let me know if you have any doubts or errors.

Cheers

Upvotes: 1

Related Questions