Text to appear as checkbox is clicked in Python Tkinter - python

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

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:

simple tkinter question - button command (display other text on click)

i've just started learning tkinter for python, and i'm trying to get the button to change its text when it's clicked on.
this seems like a very simple question, but i can't find any answers. the code i'm using at the moment doesn't work - when the window opens, it displays 'clicked!' as a label above the button immediately, before i've clicked on the button.
from tkinter import *
root = Tk()
def click():
label = Label(root, text = 'clicked!')
label.pack()
button = Button(root, text='click me', command = click())
button.pack()
root.mainloop()
To change an existing button's text (or some other option), you can call its config() method and pass it keyword arguments with new values in them. Note that when constructing the Button only pass it the name of the callback function — i.e. don't call it).
from tkinter import *
root = Tk()
def click():
button.config(text='clicked!')
button = Button(root, text='click me', command=click)
button.pack()
root.mainloop()
You're passing command = click() to the Button constructor. This way, Python executes click, then passes its return value to Button. To pass the function itself, remove the parentheses - command = click.

Checkbutton on tkinter retains it's value no matter what

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

OptionMenu widget not updating when StringVar is changed until hovered

I need a menu that can respond to items being clicked by running code then switch the text back to a default text.
Currently, my implementation works but the default text is only displayed when the cursor hovers over the menu after clicking.
I have searched but I could not find anything related to this problem, although maybe that is because I am unsure as to what exactly is causing this.
Here is the code to reproduce this behaviour:
from tkinter import *
root = Tk()
default_text = 'select an item'
def thing_selected(self, *args):
#other stuff happens here
var.set(default_text)
var = StringVar(root)
var.set(default_text)
var.trace('w', thing_selected)
menu = OptionMenu(root, var, *['Pizza','Lasagne','Fries','Fish'])
menu.pack()
root.mainloop()
Here is a gif representing the outcome:
I would expect the text at the top to be updated instantaneously, but it only updates when the cursor has hovered over the widget
I am looking for some way to trigger a hover event on the widget or I am open to suggestions for any other methods of accomplishing this.
You could take a different route and use the command attribute of the OptionMenu:
import tkinter as tk
root = tk.Tk()
default_text = 'select an item'
def thing_selected(selected):
#other stuff happens here
print(var.get())
var.set(default_text)
print(var.get())
var = tk.StringVar()
var.set(default_text)
options = ['Pizza','Lasagne','Fries','Fish']
menu = tk.OptionMenu(root, var, *options, command = thing_selected)
menu.pack()
root.mainloop()

How to make widgets visible again when using pack_forget in Tkinter

I have this code:
# -*- coding: utf-8 -*-
def clear_screen():
button2.pack_forget()
button3.pack_forget()
text.pack_forget()
label.pack_forget()
def main_page():
var = StringVar()
label = Label( root, textvariable=var)
var.set("Fill in the caps: ")
label.pack()
global text
text = Text(root,font=("Purisa",12))
text.pack()
global button
button=Button(root, text ="Create text with caps.", command =lambda: full_function())
button.pack()
def clear_and_main():
clear_screen()
main_page()
def full_function():
global button2
global button3
button3=Button(root, text ="Main page", command=lambda: clear_and_main())
button3.pack()
button2=Button(root, text ="Answer")
button2.pack()
button.pack_forget()
from Tkinter import *
root = Tk()
main_page()
root.mainloop()
I want this program to work that way, if I click button "Main page", it will recreate main page. But it doesn't. Textfield and button wont reappear. How could I make it work right way?
You are neglecting to declare text and label as global, so clear_screen is failing.
Calling pack_forget does not destroy widgets, it only hides them. Your code creates new widgets every time which means you have a memory leak -- you keep creating more and more and more widgets every time you click the button.
The easiest way to accomplish what you want is to put all of the widgets in a frame, and then destroy and recreate the frame. When you destroy a widget, any children widgets automatically get destroyed. This also makes it easier to maintain, since you don't have to change anything if you add more widgets.

Categories

Resources