Checkbutton on tkinter retains it's value no matter what - python

I'm trying to get the value from Checkbutton on tkinter but it retains the original value. I have tried what people say on countless forums including this one but nothing works, it just retains the value i give it with var.set(True) or var.set(False). This chechbutton is on a pop up window btw, but it's not global, it's just defined on said window. this is my code:
import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk()
root.geometry('500x500')
var = tk.BooleanVar()
var.set(False)
startup = tk.Checkbutton(root, variable=var, onvalue=True, offvalue=False , text = "test")
when ver i use var.get() i get the initial value. help me plz :( Thanks in advice.

The reason is because Checkbutton requires a callback function to change the state of the button.
def toggle(button):
if button.get() is True:
button.set(True)
else:
button.set(False)
The you would use the callback function in the instantiation of the Checkbutton
startup = tk.Checkbutton(root, variable=var, text = "test",
command=lambda button=var: toggle(button))

Related

Python tkinter kept saying my variable to hold the .get() value is not defined

I am learning how to use the .get() for tkinter, and trying to write this basic GUI that can store, process, and display data depending on a user input.
Now (I am fairly new to this, so I am probably wrong) to my knowledge, I need to use the .get() and store it into a variable for future uses.
Now here are my codes, but when I run the code, it kept saying I did not define my variable in the function I defined.
I wrote in Pycharm, the variable I wrote in the first line of the function just keep turning grey.
Why is this happening, am I missing something important?
Sidenote:
I have done some research and saw some result regarding using the following method:
StringVar()
fstring, f"{}"
but I still can't figure out how that works and how it is affecting my code that Python is not accepting my variable.
Import tkinter as tk
def event():
expEntry = entry.get()
window = tk.Tk()
entry = tk.Entry(window)
button = tk.Button(window,commnad=event())
expEntry = tk.Label(window,text = expEntry)
entry.pack()
button.pack()
expEntry.pack()
window.mainloop()
You should use a StringVar to store the value of the entry when event() is called by button
import tkinter as tk
def event(): # use this function to update the StringVar
entry_content = entry.get()
entry_var.set(entry_content)
window = tk.Tk()
# declare a StringVar to store the value of your Entry and update your Label
entry_var = tk.StringVar(window, 'Default Text')
# use 'textvariable' here to update the label when the bound variable changes
expEntry = tk.Label(window, textvariable=entry_var)
entry = tk.Entry(window)
# there was a typo in 'command' here, FIY
button = tk.Button(window, text='Press me', command=event)
entry.pack()
button.pack()
expEntry.pack()
window.mainloop()
Note: you don't need the () for the command binding, as you're not calling the event function there! You're just telling the button the name of the function it should call.
Easier way to do this. Just added tk.StringVar().
import tkinter as tk
window = tk.Tk()
window.geometry("700x300")
window.title("StringVar Object in Entry Widget")
var =tk.StringVar(window)
def event():
Label2.config(text=var.get())
myEntry = tk.Entry(window, textvariable=var)
myEntry.pack()
myButton = tk.Button(window, text="Submit", command=event)
myButton.pack()
Label2 = tk.Label(window, font="Calibri,10")
Label2.pack()
window.mainloop()
Output before:
Output after:

How do I destroy a tkinter frame?

I am trying to make a tkinter frame that will contain an entry field and a submit button. When the submit button is pressed, I want to pass the entry string to the program and destroy the frame. After many experiments, I came up with this script:
from tkinter import *
from tkinter import ttk
import time
root = Tk()
entryframe = ttk.Frame(root)
entryframe.pack()
par = StringVar('')
entrypar = ttk.Entry(entryframe, textvariable=par)
entrypar.pack()
submit = ttk.Button(entryframe, text='Submit', command=entryframe.quit)
submit.pack()
entryframe.mainloop()
entryframe.destroy()
parval = par.get()
print(parval)
time.sleep(3)
root.mainloop()
When the "Submit" button is pressed, the parameter value is passed correctly to the script and printed. However, the entry frame is destroyed only after 3 seconds (set by the time.sleep function).
I want to destroy the entry frame immediately.
I have a slightly different version of the script in which the entry frame does get destroyed immediately (although the button itself is not destroyed), but the value of par is not printed:
from tkinter import *
from tkinter import ttk
import time
root = Tk()
entryframe = ttk.Frame(root)
entryframe.pack()
par = StringVar('')
entrypar = ttk.Entry(entryframe, textvariable=par)
entrypar.pack()
submit = ttk.Button(root, text='Submit', command=entryframe.destroy)
submit.pack()
entryframe.mainloop()
# entryframe.destroy()
parval = par.get()
print(parval)
time.sleep(3)
root.mainloop()
How can I get both actions, namely the entry frame destroyed immediately and the value of par printed?
Note 100% sure what you are trying to do but look at this code:
from tkinter import *
from tkinter import ttk
def print_results():
global user_input # If you want to access the user's input from outside the function
# Handle the user's input
user_input = entrypar.get()
print(user_input)
# Destroy whatever you want here:
entrypar.destroy()
submit.destroy()
# If you want you can also destroy the window: root.destroy()
# I will create a new `Label` with the user's input:
label = Label(root, text=user_input)
label.pack()
# Create a tkitner window
root = Tk()
# Create the entry
entrypar = ttk.Entry(root)
entrypar.pack()
# Create the button and tell tkinter to call `print_results` whenever
# the button is pressed
submit = ttk.Button(root, text="Submit", command=print_results)
submit.pack()
# Run tkinter's main loop
# It will stop only when all tkinter windows are closed
root.mainloop()
# Because of the `global user_input` now we can use:
print("Again, user_input =", user_input)
I defined a function which will destroy the entry and the button. It also creates a new label that displays the user's input.
I was able to accomplish what I wanted using the wait_window method. Here is the correct script:
from tkinter import *
from tkinter import ttk
root = Tk()
entryframe = ttk.Frame(root)
entryframe.pack()
entrypar = ttk.Entry(entryframe)
entrypar.pack()
submit = ttk.Button(entryframe, text='Submit', command=entryframe.destroy)
submit.pack()
entrypar.wait_window()
parval = entrypar.get()
print(parval)
close_button = ttk.Button(root, text='Close', command=root.destroy)
close_button.pack()
root.mainloop()
My intention was not fully apparent in my original question, and I apologize for that. Anyway, the answers did put me on the right track, and I am immensely thankful.

Text to appear as checkbox is clicked in Python Tkinter

I am coding a GUI in Python 2.7 and I am making checkboxes. I want to know how to make a text appear right beside the checkbox when it is checked and unchecked. For eg. When I check the checkbox the text beside the checkbox should be 'enable' and when I uncheck the checkbox the text should be 'disable'.
You can assign same StringVar to textvariable and variable options of Checkbutton and set onvalue='enable' and offvalue='disable'. Then whenever the state of the checkbutton changes, the text changes:
import tkinter as tk
root = tk.Tk()
var = tk.StringVar(value='disable')
tk.Checkbutton(root, textvariable=var, variable=var, onvalue='enable', offvalue='disable').pack()
root.mainloop()
There's nothing particularly difficult about this. Checkbuttons can call a command when toggled. You can change the text inside the command using the configure method of the widget.
Here's a simple example:
import tkinter as tk
def toggle(widget):
variable = widget.cget("variable")
value = int(widget.getvar(variable))
label = "enable" if value else "disable"
widget.configure(text=label)
root = tk.Tk()
for i in range(10):
cb = tk.Checkbutton(root, text="disable")
cb.configure(command=lambda widget=cb: toggle(widget))
cb.pack(side="top")
root.mainloop()

input box does not appear in tkinter window

I have an issue with tkinter. Basically When I attempt to create an input box, the window opens with the title only.
from tkinter import *
window = Tk()
window.title("name generator")
def openInterface():
inputLabel = Label(window, text="Enter your name")
inputLabel.grid(row=0, column=2)
print(inputLabel)
Am i missing something? My apologies in advance for this is a noob question.
You never call your openInterface function. Functions are different from code in the global scope becasue they only get executed when called, not when they are defined.
from tkinter import *
window = Tk()
window.title("name generator")
openInterface()
def openInterface():
inputLabel = Label(window, text="Enter your name")
inputLabel.grid(row=0, column=2)
print(inputLabel)
I think you are missing two things, you haven't call
funtion and also you you need to use
window.mainloop()

python entry widget and get method

Is there any way to put the textvariable in another variable and not have to use the ".get()"? I've been doing a lot of sifting thorugh tutorials and articles for what I realize is a very small issue but I'm probably misunderstanding something pretty key so i'm hoping someone can help me develop some intuition for the entry widget and .get() method.
Below is part of a script that I've been working on where I want to take the text entered in the entry box and use it later. I can use it if I use search_word.get(), but I don't why I can't do something like New_variable=search_word.get() so that from that point on I can just use "New_variable".
import tkinter as tk
from tkinter import *
from tkinter import ttk
Text_input_window = Tk()
Text_input_window.geometry('600x350+100+200')
Text_input_window.title("Test")
label_1=ttk.Label(Text_input_window, text="Enter word to search:", background="black", foreground="white")
label_1.grid(row=1, column=0, sticky=W)
search_word=StringVar()
entry_1=ttk.Entry(Text_input_window,textvariable=search_word, width=40, background="white")
entry_1.grid(row=2, column=0, sticky=W)
New_variable=StringVar()
New_variable=search_word.get()
def click():
print(New_variable)
print(search_word.get())
Text_input_window.destroy()
btn_1=ttk.Button(Text_input_window, text="submit", width=10, command=click)
btn_1.grid(row=3, column=0, sticky=W)
Text_input_window.mainloop()
Problem is not .get() but how all GUIs works.
mainloop() starts program so new_variable = search_word.get() is executed before you even see window - so it tries to get text before you put text in Entry.
You have to do it inside click() which is executed after you put text in entry and click button.
import tkinter as tk
# --- functions ---
def click():
global new_variable # inform function to use external/global variable instead of creating local one
#new_variable = entry.get() # you can get it directly from `Entry` without StringVar()
new_variable = search_word.get()
root.destroy()
# --- main ---
new_variable = '' # create global variable with default value
root = tk.Tk()
search_word = tk.StringVar()
entry = tk.Entry(root, textvariable=search_word)
entry.pack()
btn = tk.Button(root, text="submit", command=click)
btn.pack()
root.mainloop() # start program
# --- after closing window ---
print('new_variable:', new_variable)
print('search_word:', search_word.get()) # it seems it still exists
# print('entry:', entry.get()) # `Entry` doesn't exists after closing window so it gives error
Is there any way to put the textvariable in another variable and not have to use the ".get()"?
No, there is not. Tkinter variables are objects, not values. Anytime you want to use a value from a tkinter variable (StringVar, IntVar, etc) you must call the get method.

Categories

Resources