Here we will learn how to create an entry widget in Tkinter.
To create an entry on Tkinter, the Entry widget is used, which allows the user to enter data to be processed or saved.
Syntax
entry_1 = Entry(window, width = 10)
entry_1.grid(column = 1, row = 0)
Here, Entry will create an input field with a width of 10 pixels that has been defined with the width attribute.
So, the complete code will look like this:
from tkinter import *
window = Tk()
window. title("Entry")
window.geometry('300x300')
label = Label(window, text="First Entry")
label.grid(row=0,column=0, padx=10, pady=10)
entry = Entry (window, width=10)
entry.grid (row=0, column=1 )
window.mainloop()
We can also give space between the label and the entry using attributes such as padx and pady, padx for horizontal and pady for vertical. In the code above we used padx as 10px and pady as 10px also.
And these attributes can also be used in other widgets for the same purpose, such as Label, Button, etc.
Python tkinter - how to get data from Entry
Now we will try to get the data entered by the user using the Tkinter Entry class.
First, we will create a function, and inside it we will change the name of the label using the keyword in tkinter called configure, with this word we can change the values of an attribute that is inside a widget.
def hello():
result = entry.get()
label.configure(text = result)
In order to get the that that are entered in the entry box, we use the function get(), as showen inside the function, whre the variabel result is getting the data from the the entry box.
Next we will create a button that when it is cliked the function will be executed.
button = Button(window, text = "Click here", command = hello)
button.grid(column = 2, row = 0, padx = 5, pady = 15)
Here, the result variable is getting the data contained in the entry (entry), and label.configure is changing the name of the label, changing the current value of the text attribute to the value contained in the result variable (entry).
So, the complete code will look like this:
from tkinter import *
window = Tk()
window. title("Entry")
window.geometry('300x300')
def hello():
result = entry.get()
label.configure (text=result)
label = Label(window, text="First Entry")
label.grid(row=0,column=0, padx=10, pady=10)
entry = Entry (window, width=10)
entry.grid (row=0, column=1 )
button = Button(window, text = "Click here", command = hello)
button.grid (column = 0, row = 1, padx = 5, pady = 15)
window.mainloop()
If you click the button and there is text in the input widget, the text will be shown on the label.
Python Tkinter - Disable input widget
To disable the input widget, you can set the state property to disabled:
entry = Entry (window, width = 10, state = 'disabled')
Now, you will not be able to enter any text.
Post a Comment
0Comments