Tkinter: Link an Entry Widget to a Button to a Function - python

I am new to Tkinter and not to sure how to proceed. I am trying to link a function that I define to a entry widget that is activated by a button. but I can't figure out how to get the three to communicate to each other. I would like it to print as well as return to the script so that I can be used in another function. This is what I have so far:
import Tkinter as tk
def TestMath(x):
calculate = x + 4
print calculate
return calculate
root = tk.Tk()
entry = tk.Entry(root)
value = entry.get()
number = int(value)
button = tk.Button(root, text="Calculate")
calculation = TestMath(number)
root.mainloop()

Button calls function assigned to command= (it has to be "function name" without () and arguments - or lambda function)
TestMath assigns calculation to global variable result and other functions can have access to that value.
import Tkinter as tk
def TestMath():
global result # to return calculation
result = int(entry.get())
result += 4
print result
result = 0
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
button = tk.Button(root, text="Calculate", command=TestMath)
button.pack()
root.mainloop()
Function called by button don't have to return value because there is no object which could receive that value.

Related

I found a function a bit of code on here that works but I don't understand why it works

The code is below from this post:
Why is Tkinter Entry's get function returning nothing?
The argument in the return_entry is 'en' and when I deleted it out it says a positional argument is missing. What is the def return_entry('en') mean and why does it only work with it.
Why cant i just use:
def return_entry():
The en argument makes no sense to me...
from tkinter import *
master = Tk()
def return_entry(en):
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
Error:
TypeError: return_entry() takes 0 positional arguments but 1 was given
Only throws an error when I remove en and hit enter after I enter input in the entry box.
bind expects function which can get argument to send event to this function - and it will run it as return_entry(event). And this is why you can't use function without argument.
You can even use this event to get access to entry - so you can assing the same function to different entries and ifunction will get text from correct entry
def return_entry(event):
content = event.widget.get()
print(content)
Sometimes we may want to use the same function with command= which doesn't send event to function and then we can use event=None but then we can't use event inside function
def return_entry(event=None):
content = entry.get()
print(content)
entry.bind('<Return>', return_entry)
tk.Button(..., command=return_entry)
Working examples:
Function binded to two entries:
import tkinter as tk
def return_entry(event):
content = event.widget.get()
print(content)
root = tk.Tk()
entry1 = tk.Entry(root)
entry1.pack()
entry1.bind('<Return>', return_entry)
entry2 = tk.Entry(root)
entry2.pack()
entry2.bind('<Return>', return_entry)
root.mainloop()
Function assigned to Entry and Button
import tkinter as tk
def return_entry(event=None):
content = entry.get()
print(content)
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
entry.bind('<Return>', return_entry)
button = tk.Button(root, text='OK', command=return_entry)
button.pack()
root.mainloop()

Change label text on button using values from tuple click tkinter

I have a list of strings sorted in a tuple like this:
values = ('1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript')
My simple code is:
from tkinter import *
root = Tk()
values = ('1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript')
ru = Button(root,
text="Next",
)
ru.grid(column=0,row=0)
lab = Label(root,
text=values[0])
lab.grid(column=1,row=0)
ru2 = Button(root,
text="Previous"
)
ru2.grid(column=2,row=0)
root.mainloop()
I have two tkinter buttons "next" and "previous", the text value of the Label is directly taken from the tuple (text=value[0]), however I would want to know how to show the next string from the tuple when the next button is pressed, and how to change it to the previous values when the "previous" button is pressed. I know it can be done using for-loop but I cannot figure out how to implement that. I am new to python.
Use Button(..., command=callback) to assign function which will change text in label lab["text"] = "new text"
callback means function name without ()
You will have to use global inside function to inform function to assign current += 1 to external variable, not search local one.
import tkinter as tk
# --- functions ---
def set_next():
global current
if current < len(values)-1:
current += 1
lab["text"] = values[current]
def set_prev():
global current
if current > 0:
current -= 1
lab["text"] = values[current]
# --- main ---
values = ('1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript')
current = 0
root = tk.Tk()
ru = tk.Button(root, text="Next", command=set_next)
ru.grid(column=0, row=0)
lab = tk.Label(root, text=values[current])
lab.grid(column=1, row=0)
ru2 = tk.Button(root, text="Previous", command=set_prev)
ru2.grid(column=2, row=0)
root.mainloop()
BTW: if Next has to show first element after last one
def set_next():
global current
current = (current + 1) % len(values)
lab["text"] = values[current]
def set_prev():
global current
current = (current - 1) % len(values)
lab["text"] = values[current]

Get function tkinter

I use tkinter on python 2.7. My problem is that I don't succeed in getting the variable entered into the entry_number; the function is called, but it didn't print anything.
How can I know if the checkbox is checked or not?
from tkinter import *
from tkinter import Tk, StringVar, Label, Entry, Button
def call():
print (e)
root = Tk()
var1 = IntVar()
c=Checkbutton(root, text="Bou ", variable=var1).grid(row=4, column=1)
text = StringVar(root)
button = Button(root, text='call',
command=call)
entry_number = Entry(root)
button.grid(column=8, row=20)
entry_number.grid(column=6,row=4)
e = entry_number.get()
root.mainloop()
The problem is that you define e immediately when you are creating the UI. At this point, the entry is still empty, so all that is printed when you press the button is an empty string.
Instead, put the definition of e inside the function, so it is updated each time you click:
def call():
e = entry_number.get()
print (e)

tkinter Checkbutton widget returning wrong boolean value

I have a simple GUI here that's suppose to return a boolean value depending on whether the check button is checked or not. I've set the boolean variable to False hence the empty check button. What I don't understand is that when I check the button, the function binded to that widget returns a False instead of True. Why is that?
Here's the code...
from tkinter import *
from tkinter import ttk
def getBool(event):
print(boolvar.get())
root = Tk()
boolvar = BooleanVar()
boolvar.set(False)
cb = Checkbutton(root, text = "Check Me", variable = boolvar)
cb.bind("<Button-1>", getBool)
cb.pack()
root.mainloop()
when checking the empty button the function outputs...
False
Shouldn't it return True now that the button is checked?
The boolean value is changed after the bind callback is made. To give you an example, check this out:
from tkinter import *
def getBool(event):
print(boolvar.get())
root = Tk()
boolvar = BooleanVar()
boolvar.set(False)
boolvar.trace('w', lambda *_: print("The value was changed"))
cb = Checkbutton(root, text = "Check Me", variable = boolvar)
cb.bind("<Button-1>", getBool)
cb.pack()
root.mainloop()
When you presses the Checkbutton, the first output is False then it's "The value was changed", which means that the value was changed after the getBool callback is completed.
What you should do is to use the command argument for the setting the callback, look:
from tkinter import *
def getBool(): # get rid of the event argument
print(boolvar.get())
root = Tk()
boolvar = BooleanVar()
boolvar.set(False)
boolvar.trace('w', lambda *_: print("The value was changed"))
cb = Checkbutton(root, text = "Check Me", variable = boolvar, command = getBool)
cb.pack()
root.mainloop()
The output is first "The value was changed" then True.
For my examples, I used boolvar.trace, it runs the lambda callback when the boolean value changes ('w')

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()

Categories