How to use textfield key press event using python - python

if i write some thing on the textfield and press enter key on the keyboard.what i entered on the textfield display messagebox. this point get error if(format(k=event.char(13)))) : if i set the enter key code. i added full code below.
from tkinter import *
root = Tk()
root.geometry("800x800")
global e1
def callback(event):
if(format(k=event.char(13)))):
msg = e1.get()
print(msg)
Label(root, text="Student Name").place(x=140, y=40)
e1 = Entry(root)
e1.place(x=140, y=10)
e1.bind('<Key>',callback)
root.mainloop()

Try this out
from tkinter import *
root = Tk()
root.geometry("800x800")
def callback(event):
msg = e1.get()
print(msg)
Label(root, text="Student Name").place(x=140, y=40)
e1 = Entry(root)
e1.place(x=140, y=10)
e1.bind('<Return>',callback) #<Return> is equivalent to your Enter key
root.mainloop()
When you click on Enter key, on the entry widget, then the function gets called and the output will be printed out. I also removed the global as it makes no sense to use it in outside functions.
Hope it helped you out.
Cheers

Related

Returning a value when clicking a button in tkinter

I have created a simple text box and want to take the text from it when i click on a button, but for some reason it doesn't work. I tried using a global variable but it still doesn't work.
Here is what i have written sofar:
t = Text(r, height=20, width=40)
t.pack()
def myClick():
myLabel= Label(r,text= "Sent!")
global input
input = t.get("1.0", 'end-1c')
myLabel.pack()
myButton = Button(r, text="Send ", command=myClick)
myButton.pack()
print(input)
r.mainloop()
I think you are using too many arguments in the .get() and the widget type has to be Entry and you really should define your variable before everything else. Here is my suggestion for your code:
from tkinter import *
r = Tk()
t = Entry(r, width=40)
t.pack()
def myClick():
global input
input = t.get()
myLabel= Label(r,text= input)
myLabel.pack()
myButton = Button(r, text="Send ", command=myClick)
myButton.pack()
print(input)
r.mainloop()

I having trouble running my python Tkinter question

I'm working on a python assignment and this is where I got so far. I'm stuck and cannot execute the application. I'm making a calculator that scores the average and gives a grade letter. I was looking into my professor's video and there was "import tkinter.messagebox as tkm" but Im not sure how to implement this in the code.
this is my code:
import tkinter as tk
import tkinter.messagebox as tkm
window = tk.Tk()
window.geometry('400x400')
window.title("Exam Calculator")
window = tk.Tk()
window.geometry('300x300')
def calculate():
score1 = float(entry1.get())
score2 = float(entry2.get())
score3 = float(entry3.get())
avg = (score1 + score2 + score3)/3
if(avg>=90):
lettergrade= "A"
elif(avg>=80 and avg<=89):
lettergrade = "B"
elif(avg>=70 and avg<=79):
lettergrade= "C"
elif(avg>=60 and avg<=69):
lettergrade = "D"
else:
lettergrade = "F"
label1 = tk.Label(window, text='Test 1')
label1.pack()
entry1 = tk.Entry(window)
entry1.pack()
label2 = tk.Label(window, text='Test 2')
label2.pack()
entry2 = tk.Entry(window)
entry2.pack()
label3 = tk.Label(window, text='Test 3')
label3.pack()
entry3 = tk.Entry(window)
entry3.pack()
button2 = tk.Button(window, text="Calculate",
command=calculate)
Button1 = tk.Button(window, text="quit",
command=window.destroy)
messagebox can help to create fast small message windows.
The usage is very simple, just implement this in your code:
from tkinter import messagebox
In you case:
from tkinter import messagebox as tkm
Then:
messagebox.function(title,message,options)
In your case:
tkm.function(title,message,options)
The functions are:
showinfo(): for showing some relevant informations.
showwarning(): for displaying a warning to the user.
showerror(): for displaying an error message.
askquestion(): for asking a yes/no question to the user.
askokcancel(): confirm the user’s action regarding some application
activity.
askyesno(): for asking a yes/no question about a user action.
askretrycancel(): for asking the user about doing a specific task again.
The options are:
default: this option is used to specify the default button like
ABORT, RETRY, or IGNORE in the message box.
parent: this option is used to specify the window on top of which
the message box is to be displayed.
The code needs just some improvements:
pack() the two buttons (as to display them)
add window.mainloop() at the end of your code (this is why is does not start)
There are multiple problems in your code. First, you define window two times. The second time, you just override your frist instance of window, so just leave that out.
Then you are not packing your Buttons, which means they will not be shown in your window. Lastly, you are missing the most important part of your Tkinter Application, which is to start the applications mainloop, which makes the window pop up and tells Tkinter to start listening for your mouse and keyboard interaction with the window and do something with it. This is called an event loop and is the main component of every graphical user interface. You start the eventloop by calling .mainloop() on your instance of tk.Tk, which is your window variable.
Lastly, it is unclear from your text what you actually want to do with the Messagebox.
I assume that you want to use the message box to display the result of your calculate function, since right now it doesn't do anything.
import tkinter as tk
import tkinter.messagebox as tkm
window = tk.Tk()
window.geometry('400x400')
window.title("Exam Calculator")
def calculate():
score1 = float(entry1.get())
score2 = float(entry2.get())
score3 = float(entry3.get())
avg = (score1 + score2 + score3)/3
if(avg>=90):
lettergrade= "A"
elif(avg>=80 and avg<=89):
lettergrade = "B"
elif(avg>=70 and avg<=79):
lettergrade= "C"
elif(avg>=60 and avg<=69):
lettergrade = "D"
else:
lettergrade = "F"
message = 'Your result is ' + lettergrade
tkm.showinfo(title='Result', message=message)
label1 = tk.Label(window, text='Test 1')
label1.pack()
entry1 = tk.Entry(window)
entry1.pack()
label2 = tk.Label(window, text='Test 2')
label2.pack()
entry2 = tk.Entry(window)
entry2.pack()
label3 = tk.Label(window, text='Test 3')
label3.pack()
entry3 = tk.Entry(window)
entry3.pack()
button2 = tk.Button(window, text="Calculate",
command=calculate)
button2.pack()
Button1 = tk.Button(window, text="quit",
command=window.destroy)
Button1.pack()
window.mainloop()

How do I get the Entry's value in tkinter?

I'm trying to use Tkinter's Entry widget. I can't get it to do something very basic: return the entered value. Does anyone have any idea why such a simple script would not return anything? I've tried tons of combinations and looked at different ideas.
This script runs but does not print the entry:
from Tkinter import *
root = Tk()
E1 = Entry(root)
E1.pack()
entry = E1.get()
root.mainloop()
print "Entered text:", entry
Seems so simple.
Edit
In case anyone else comes across this problem and doesn't understand, here is what ended up working for me. I added a button to the entry window. The button's command closes the window and does the get() function:
from Tkinter import *
def close_window():
global entry
entry = E.get()
root.destroy()
root = Tk()
E = tk.Entry(root)
E.pack(anchor = CENTER)
B = Button(root, text = "OK", command = close_window)
B.pack(anchor = S)
root.mainloop()
And that returned the desired value.
Your first problem is that the call to get in entry = E1.get() happens even before your program starts, so clearly entry will point to some empty string.
Your eventual second problem is that the text would anyhow be printed only after the mainloop finishes, i.e. you close the tkinter application.
If you want to print the contents of your Entry widget while your program is running, you need to schedule a callback. For example, you can listen to the pressing of the <Return> key as follows
import Tkinter as tk
def on_change(e):
print e.widget.get()
root = tk.Tk()
e = tk.Entry(root)
e.pack()
# Calling on_change when you press the return key
e.bind("<Return>", on_change)
root.mainloop()
from tkinter import *
import tkinter as tk
root =tk.Tk()
mystring =tk.StringVar(root)
def getvalue():
print(mystring.get())
e1 = Entry(root,textvariable = mystring,width=100,fg="blue",bd=3,selectbackground='violet').pack()
button1 = tk.Button(root,
text='Submit',
fg='White',
bg= 'dark green',height = 1, width = 10,command=getvalue).pack()
root.mainloop()

defining "user" from an input box in python 2.7.8

im trying to make some code, so that when you type your name into the input box and hit the ok button, your name is then retrieved, and used as the text in a picture, my code is below.
from Tkinter import *
c = Canvas(width=500, height=500, bg='white')
c.pack(expand=YES, fill=BOTH)
master = Tk()
var = StringVar(master)
var.set("one") # initial value
option = OptionMenu(master, var, "one", "two", "three", "four")
option.pack()
#
def ok():
print "value is", var.get()
master.quit()
user = var.get() ##### this is what im struggling with
button = Button(master, text="OK", command=ok)
user = var.get()
c.create_text(200,470,text="by "+user, anchor=N, justify=CENTER) # credits
mainloop()
I think I know what you want to do? I have made some code which you enter your name into an entry box, when you hit ok your name is made into a label on the same tk window as the entry box.
Here is the code:
from Tkinter import *
master = Tk()
label = Label(text='please enter you name:')
label.pack()
entry = Entry()
entry.pack()
def ok():
type = ('Times', 20)
name = entry.get()
Label(text = name, font = type).pack()
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
give it a try and tell me if this is what you wanted or not!

Accepting inputs from Tkinter

I want to write a GUI in Tkinter that accepts a text inputs from the user and stores it in a variable Text; I also want to be able to use this variable later on... Here is something i tried that failed:
from Tkinter import *
def recieve():
text = E1.get()
return text
top = Tk()
L1 = Label(top, text="User Name")
L1.pack(side=LEFT)
E1 = Entry(top, bd=5)
E1.pack(side=RIGHT)
b = Button(top, text="get", width=10, command=recieve)
b.pack()
print text
top.mainloop()
So how do I do this?
The problem lies here:
print text
top.mainloop()
Before top.mainloop() is called, text has not been defined. Only after the call to top.mainloop is the user presented with the GUI interface, and the mainloop probably loops many many times before the user gets around to typing in the Entry box and pressing the Button. Only after the button is pressed is recieve (sic) called, and although it returns a value, that value is not stored anywhere after recieve ends. If you want to print text, you have to do it in the recieve function:
from Tkinter import *
def receive():
text = E1.get()
print(text)
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
b = Button(top, text="get", width=10, command=receive)
b.pack()
top.mainloop()

Categories