can not get the variable output in tkinter checkbutton - python

I am new to tkinter and learning to use the widget "CheckButton".
I have encountered a problem, whatever I select, the code prints 0.
Wanted:
print 1 if selected
print 0 if not selected
MWE
import tkinter as tk
win = tk.Tk()
win.title('My Window')
win.geometry('100x100')
l = tk.Label(win, width=20, text='MultipleReplace')
l.pack()
var_cb1 = tk.IntVar()
var_cb1.set(0)
cb1 = tk.Checkbutton(win, text='Yes',variable=var_cb1,onvalue=1,offvalue=0)
cb1.pack(side=tk.TOP)
var_cb1_val = var_cb1.get()
print('The selected value is : ', var_cb1_val)
win.mainloop()

You're calling get on var_cb1 pretty much immediately after setting it to 0, and then printing that value. You're not waiting for the checkbutton to change states and then printing the value. Define a function that gets called when the CheckButton changes state, then get the value there
import tkinter as tk
def on_update(var):
print('The selected value is: ', var.get()) # get the new value
win = tk.Tk()
win.title('My Window')
win.geometry('100x100')
l = tk.Label(win, width=20, text='MultipleReplace')
l.pack()
var_cb1 = tk.IntVar()
var_cb1.set(0)
cb1 = tk.Checkbutton(
win,
text='Yes',
variable=var_cb1,
onvalue=1,
offvalue=0,
# call 'on_update', using a lambda to pass in the 'var_cb1' variable
command=lambda var=var_cb1: on_update(var)
)
cb1.pack(side=tk.TOP)
win.mainloop()

Related

Tkinker spinbox get

I'd like to print output value from spinbox, after clicking enter. I don't know why it is printing always value "from_" (so 1). What is the problem? Thank you.
import tkinter as tk
gui = tk.Tk()
gui.geometry("300x390")
gui.title("Test")
var = tk.IntVar()
tk.Spinbox(
gui,
textvariable=var,
from_=1,
to=10).pack()
a = var.get()
def print_test():
print(a)
enter = tk.Button(gui, text="Enter", command=print_test).pack(pady=15)
gui.mainloop()

Tkinter: update Text widget from variable

I have a variable that is updated on a button click, and I want to show the variable's value in a Text widget, but I'm getting a blank every time despite checking that the variable is not empty.
I'm using a StringVar called var as a middle man but the result is still blank.
from tkinter import *
import time
var = None
def get_tags():
tag_info={'hashtags':"Loading..."}
var.set(str(tag_info.get('hashtags','')))
if __name__ == '__main__':
root = Tk()
root.title("Tag Generator")
var = StringVar(root)
show_button = Button(root, text='Show',
command=lambda: get_tags())
show_button.grid(column=2,columnspan=1, padx=5, pady=5, row=num+1)
result_text = Text(root)
result_text.grid(column=0,columnspan=3, padx=5, pady=5, row=num+2, rowspan=4)
result_text.insert('1.0',var.get())
while True:
time.sleep(0.01)
root.update()
How can I show the contents of var in my Text widget?
EDIT:contents of my var variable:
var.get()
Out[86]: '.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n#cat #dog #catsofinstagram #cats #pet #dogsofinstagram #catlover #cute #love #dogs #pets #catstagram #instagood #puppy #kitty #animals #petstagram #dogstagram #gato #kitten #animal #instadog #catoftheday #doglover #cats_of_instagram #adorable #instagram #dogoftheday #instacat #meow '
(which is as expected/desired)
The text is not showing because the var = '' at line result_text.insert('1.0',var.get())and you can't press the Button before mainloop so by putting the same line in function get_tags() should solve the issue.
But at this point I'm wonder why you even need var. If you're not using it for anything else then you should remove it and insert in the Text directly.
def get_tags():
tag_info={'hashtags':"Loading..."}
tag_info = my_file.get_tags()
var.set(str(tag_info.get('hashtags','')))
result_text.insert('1.0', var.get())

tkinter 'var' for radiobutton is always returning 0

from the List of radio button I want to know which one was clicked
Whenever a radio button (In python Tkinter) is clicked its returning 0...
I tried the following method:
declaring the 'var' variable global
passing var variable in all function
But none of the steps are working
def get_date(var):
path_read = E1.get()
date_list = readunparseddata.getdate_unparseddate(path_read)
show_date(date_list,var)
def show_date(list_date,var):
print(var)
frame = Tk()
#v.set(1)
Label(frame,text="""Choose your Date :""",justify=LEFT,padx=20).pack( anchor = W )
count = 0
for date in list_date:
print count
R1=Radiobutton(frame, text=date, padx=20, value=count, variable=var, command=lambda:ShowChoice(var))
R1.pack()
count+=1
def ShowChoice(var):
print "option : " + str(var.get())
top = Tk()
var=IntVar()
The problem was with the instance of Tk() that I was creating.
Below link ( 1 ) said to use TopLevel() which solved the problem
Increment the counter in the function that is being called when the radio button is selected.
Here is an example to help you.It prints the number of times the button is selected.
import Tkinter as tk
count=0
root = tk.Tk()
def add():
global count
count=count+1
print count
v = tk.IntVar()
tk.Label(root,
text="""Choose a
programming language:""",
justify = tk.LEFT,
padx = 20).pack()
tk.Radiobutton(root,
text="Python",
padx = 20,
variable=v,
value=1,command=add).pack(anchor=tk.W)
root.mainloop()

Changing the content of a label after a checkbox is selected in Tkinter

I have a label that is coded like this that contains text that is set upon running the program.
label_text = StringVar()
label = Label(window,textvariable=label_text)
label_text.set("Off")
I also have a checkbox;
var= IntVar()
Check= Checkbutton(window,text = "On",variable = var,onvalue = 1,offvalue = 0)
These are both packed like this:
label.pack()
Check.pack(side="left")
When the checkbox is checked, I want to have the label change text to "On",
something like this.
if var.get()==1:
label_text.set("On")
The text remains at Off when I check the checkbox. Any help would be appreciated.
There are several ways of updating the label text when the checkbutton state changes.
One possibility is to make the label and the checkbutton share the same StringVar and set the onvalue/offvalue of the checkbutton to "On"/"Off". That way, when the state of the checkbutton changes, the text of the label is automatically updated.
from tkinter import StringVar, Tk, Label, Checkbutton
window = Tk()
label_text = StringVar()
label = Label(window, textvariable=label_text)
label_text.set("Off")
check= Checkbutton(window, text="On", variable=label_text,
onvalue="On", offvalue="Off")
label.pack()
check.pack(side="left")
window.mainloop()
If for some reason you really want the onvalue/offvalue of the checkbutton to be 0/1, you can pass a function to the command option of the checkbutton. This function will change the text of the label depending on the state of the checkbutton.
from tkinter import StringVar, Tk, Label, Checkbutton, IntVar
def update_label():
if var.get() == 1:
label_text.set("On")
else:
label_text.set("Off")
window = Tk()
label_text = StringVar()
label = Label(window, textvariable=label_text)
label_text.set("Off")
var = IntVar()
check= Checkbutton(window, text="On", variable=var,
onvalue=1, offvalue=0, command=update_label)
label.pack()
check.pack(side="left")
window.mainloop()

In Tkinter, How I disable Entry?

How I disable Entry in Tkinter.
def com():
....
entryy=Entry()
entryy.pack()
button=Button(text="Enter!", command=com, font=(24))
button.pack(expand="yes", anchor="center")
As I said How I disable Entry in com function?
Set state to 'disabled'.
For example:
from tkinter import *
root = Tk()
entry = Entry(root, state='disabled')
entry.pack()
root.mainloop()
or
from tkinter import *
root = Tk()
entry = Entry(root)
entry.config(state='disabled') # OR entry['state'] = 'disabled'
entry.pack()
root.mainloop()
See Tkinter.Entry.config
So the com function should read as:
def com():
entry.config(state='disabled')
if we want to change again and again data in entry box we will have to first convert into Normal state after changing data we will convert in to disable state
import tkinter as tk
count = 0
def func(en):
en.configure(state=tk.NORMAL)
global count
count += 1
count=str(count)
en.delete(0, tk.END)
text = str(count)
en.insert(0, text)
en.configure(state=tk.DISABLED)
count=int(count)
root = tk.Tk()
e = tk.Entry(root)
e.pack()
b = tk.Button(root, text='Click', command=lambda: func(e))
b.pack()
root.mainloop()

Categories