Checkbutton does not work on a nested tkinter window - python

I am trying to create a Tkinter window with a button which when clicked will provide with a new window. The new window has a checkbox and I want some actions to be done based on the checkbox value.
from tkinter import *
from tkinter import messagebox
def my_command():
def run():
pass
def cb_command():
f1 = fname1.get()
messagebox.showinfo("First Name", f1)
if cbVar.get() == 1:
messagebox.showinfo(cbVar.get())
my_button['state'] = 'active'
else:
messagebox.showinfo("Not found!")
my_button['state'] = 'disabled'
root = Tk()
root.geometry("200x200")
fname = Label(root, text="First Name")
fname.grid(row= 0, column = 0, sticky = "news", padx=5, pady=5)
fname1 = Entry(root, width = 10)
fname1.grid(row =0, column = 1, sticky = "news", padx=5, pady=5)
cbVar = IntVar()
cb1 = Checkbutton(root, text="Please check this", variable=cbVar, onvalue=1, offvalue=0, command=cb_command)
cb1.grid(row = 1, column = 0)
my_button = Button(root, text = "Run", bg = '#333333', fg='#ffffff', font = 'Helvetica', command = run, state='disable')
my_button.grid(row = 2, column = 0)
root.mainloop()
window = Tk()
window.geometry("200x200")
button1 = Button(window, text = "Run", command = my_command)
button1.pack()
window.mainloop()
I wrote this simple code which works fine with all other entry widgets. However, the checkbutton in the new window does not work. Can someone suggest any alternative?
Update:
Sorry, that I didn't clarify what actions to be done. I want the checkbox when clicked impact the state of the "Run" button in the toplevel window. The actual actions are based on the "Run" button.
Thank you Thingamabobs for suggesting a very simple solution. Just replaced one instance of Tk with Toplevel and it works.

from tkinter import *
def new_window():
second_window = Toplevel()
def checkbutton_checked():
# If you just want to take some action, once the checkbutton has been checked, you could do this here
# Alternatively you could also add a button to the toplevel and on click check the value of
# the checkbutton and perform actions based on that...
cb1.configure(text="Checkbutton checked")
cb1 = Checkbutton(second_window, text="Check here", command=checkbutton_checked)
cb1.pack()
window = Tk()
b1 = Button(window, text="Open new window", command=new_window)
b1.pack()
window.mainloop()
I hope this provides some help and you can solve your problem, if not let me know please.
Further details about the purpose of the checkbutton would also help me.

Related

Tkinter Entry widget is returning an empty list when used in a toplevel window

I am attempting to open a new window when the New Window button is pressed in the main "root" window. This currently works and does indeed open a second window. In the second window I want to ask the user for an input and then this input will be turned into a list of strings.
An example input would be "Amy, Bob, Carl". The expected output would be ['Amy', 'Bob', 'Carl'] but currently the program just returns [''].
My current code is:
from tkinter import *
root = Tk()
root.title("Welcome screen")
root.geometry("300x300")
def open_new_window():
top = Toplevel()
top.title("second window")
entities = Entry(top)
entries = entities.get().split(", ")
entities.pack()
entities.focus_set()
print(entries)
sub_button = Button(top, text="Submit", command= ?)
sub_button.pack(pady=20)
close_btn = Button(top, text="Close", command=top.destroy)
close_btn.pack()
open_button = Button(root, text="New Window", command=open_new_window)
open_button.pack(pady=20)
exit_button = Button(root, text="Close", command=root.destroy)
exit_button.pack(pady=20)
root.mainloop()
I am new to Tkinter and I am unsure why this is happening. I'm sure it's a simple silly mistake but I can't find where I am going wrong. I also am unsure as to whether I need a Submit button as I don't know what command should be passed to it.
Any advice is appreciated. Please let me know if any additional information is required.
First, we will understand why you got a empty list: your code is executed sequentially, so when you do the entities.get() you haven't yet written anything nor pressed "Submit", i.e., you want to read the entry box once you press the "Submit", not earlier, for that reason, you have the command = ?.
As I am aware, you have mainly 2 options:
Get the text from the button itself
Create a variable linked to the entry box and read this
Method 1: read the data from the entry
from tkinter import *
root = Tk()
root.title("Welcome screen")
root.geometry("300x300")
def do_stuff(entry):
print(entry.get())
def open_new_window():
top = Toplevel()
top.title("second window")
entities = Entry(top)
entities.pack()
entities.focus_set()
sub_button = Button(top, text="Submit", command= lambda: do_stuff(entities))
sub_button.pack(pady=20)
close_btn = Button(top, text="Close", command=top.destroy)
close_btn.pack()
open_button = Button(root, text="New Window", command=open_new_window)
open_button.pack(pady=20)
exit_button = Button(root, text="Close", command=root.destroy)
exit_button.pack(pady=20)
root.mainloop()
Method 2: link a variable
from tkinter import *
root = Tk()
root.title("Welcome screen")
root.geometry("300x300")
def do_stuff(text_entry):
print(text_entry.get())
def open_new_window():
top = Toplevel()
top.title("second window")
text_entry = StringVar()
entities = Entry(top, textvariable = text_entry)
entities.pack()
entities.focus_set()
sub_button = Button(top, text="Submit", command= lambda: do_stuff(text_entry))
sub_button.pack(pady=20)
close_btn = Button(top, text="Close", command=top.destroy)
close_btn.pack()
open_button = Button(root, text="New Window", command=open_new_window)
open_button.pack(pady=20)
exit_button = Button(root, text="Close", command=root.destroy)
exit_button.pack(pady=20)
root.mainloop()
The main advantage in this last approach is that you can play with the text before and after the entry is built.

GUI - hiding buttons

from tkinter import *
import tkinter as tk
class dashboard(Frame):
def __init__(self, master):
super(dashboard, self).__init__(master)
self.grid()
self.buttons()
def buttons(self):
#student dashboard button
bttn1 = Button(self, text = "Student",
command=self.student, height = 2, width= 15)
bttn1.grid()
#teacher dashboard button
bttn2 = Button(self, text = "Teacher", height = 2, width= 15)
bttn2.grid()
#exit button
bttn3 = Button(self, text = "Exit",
command=root.destroy, height = 2, width= 15)
bttn3.grid()
def student(self):
#view highscores button
bttn1 = Button(self, text = "Highscores", height = 2, width= 15)
bttn1.grid()
#print score button
bttn2 = Button(self, text = "Print Score", height = 2, width= 15)
bttn2.grid()
#exit button
bttn3 = Button(self, text = "Main Menu",
command=root.destroy, height = 2, width= 15)
bttn3.grid()
#main
root = Tk()
root.title("Dashboard")
root.geometry("300x170")
app = dashboard(root)
root.mainloop()
Wondered if someone could help me basically, with this GUI I am creating I want to be able to access a new page on the same frame but the buttons from the main menu stay once I go to another page, does anyone know how I can hide/forget the buttons and go back to them at a later stage? Thanks.
Updated to use sub-Frames
You could do it using the universal grid_remove() method (here's some documentation). One way to use it would be to keep references to each of the Button widgets created so you can call this method on them as needed.
However that can be simplified slightly—even though it takes about the same amount of code—by putting all the Buttonss for each page into a separate sub-Frame and just showing or hiding it which will automatically propagate do to all the widgets it contains. This approach also provides a better foundation for the rest of your program.
I've implemented this by adding a main_button_frame attribute to your class, as well as one named student_button_frame to hold those you have on the student page (since you'll probably need it to hide them too).
One nice thing about grid_remove() is that if you later call grid() on the same widget, it will remember all the settings it (and its sub-widgets) had before it was removed, so you don't need to create and maintain a list of every single one of them yourself.
Also note I also made some general modifications to your code so it conforms to the PEP 8 - Style Guide for Python Code recommendations better. I highly recommend you read and start following it.
from tkinter import *
import tkinter as tk
class Dashboard(Frame):
def __init__(self, master):
super().__init__(master)
self.grid()
self.main_button_frame = None
self.student_button_frame = None
self.create_main_buttons()
def create_main_buttons(self):
if self.student_button_frame: # Exists?
self.student_button_frame.grid_remove() # Make it invisible.
if self.main_button_frame: # Exists?
self.main_button_frame.grid() # Just make it visible.
else: # Otherwise create it.
button_frame = self.main_button_frame = Frame(self)
button_frame.grid()
# Student Dashboard button
bttn1 = Button(button_frame, text="Student",
command=self.create_student_buttons, height=2,
width=15)
bttn1.grid()
# Teacher Dashboard button
bttn2 = Button(button_frame, text="Teacher", height=2, width=15)
bttn2.grid()
# Dashboard Exit button
bttn3 = Button(button_frame, text="Exit", command=root.destroy,
height=2, width=15)
bttn3.grid()
def create_student_buttons(self):
if self.main_button_frame: # Exists?
self.main_button_frame.grid_remove() # Make it invisible.
if self.student_button_frame: # Exists?
student_button_frame.grid() # Just make it visible.
else: # Otherwise create it.
button_frame = self.student_button_frame = Frame(self)
button_frame.grid()
# Highscores button
bttn1 = Button(button_frame, text="Highscores", height=2, width=15)
bttn1.grid()
# Print Score button
bttn2 = Button(button_frame, text="Print Score", height=2, width=15)
bttn2.grid()
# Student Exit button
bttn3 = Button(button_frame, text="Exit", command=root.destroy,
height=2, width=15)
bttn3.grid()
# main
root = Tk()
root.title("Dashboard")
root.geometry("300x170")
app = Dashboard(root)
root.mainloop()

Trying to create and configure multiple buttons from the same function in tkinter

so i'm trying to create a code which when each button is clicked it will make that button fit a certain style but with changes to the name, however my current code will replace the button you click and them when you click on another it disables the last one you clicked permanently is there anyway to make it so that the buttons all use the same function but dont get disabled when you activate another button?
from tkinter import *
MainWindow = Tk()
def SquadInfoBttnFull():
global SquadFullBttn
SquadFullBttn = Toplevel(MainWindow)
SquadFullBttn.geometry("658x600")
# -- unit buttons -- #
for i in range(10):
Unit_Button = Button(SquadFullBttn, text="EMPTY", width=8, height=6)
Unit_Button.grid(row = 0, column = i)
Unit_Button.bind("<Button-1>", UnitFill)
def SquadInfoBttn():
InfoBttn = Button(MainWindow, wraplength=50, justify=LEFT, text="SquadInfo Here", width=100, command=SquadInfoBttnFull)
InfoBttn.grid(row=0, column=0, sticky=W)
def UnitInfoBttn():
UnitInfo = Toplevel(SquadFullBttn)
UnitInfo.geometry("300x200")
def UnitFill(event):
global photo
photo = PhotoImage(file="csmSingle.png")
btn = event.widget
grid_info = event.widget.grid_info()
btn = Button(SquadFullBttn, text="UNIT", image=photo, width=58, height=93, command=UnitInfoBttn, compound = TOP)
btn.grid(row=grid_info["row"], column=grid_info["column"], sticky=E)
SquadInfoBttn()
MainWindow.mainloop()
You are trying to make changes to the existing button and not create a new one. Also, you don't need to create a new instance of PhotoImage every time. The following code works for me:
from tkinter import *
MainWindow = Tk()
photo = PhotoImage(file="csmSingle.png")
def SquadInfoBttnFull():
global SquadFullBttn
SquadFullBttn = Toplevel(MainWindow)
SquadFullBttn.geometry("658x600")
# -- unit buttons -- #
for i in range(10):
Unit_Button = Button(SquadFullBttn, text="EMPTY", width=8, height=6)
Unit_Button.grid(row = 0, column = i)
Unit_Button.bind("<Button-1>", UnitFill)
def SquadInfoBttn():
InfoBttn = Button(MainWindow, wraplength=50, justify=LEFT, text="SquadInfo Here", width=100, command=SquadInfoBttnFull)
InfoBttn.grid(row=0, column=0, sticky=W)
def UnitInfoBttn():
UnitInfo = Toplevel(SquadFullBttn)
UnitInfo.geometry("300x200")
def UnitFill(event):
btn = event.widget
grid_info = event.widget.grid_info()
btn.config(text="UNIT", image=photo, width=58, height=93, command=UnitInfoBttn, compound = TOP)
btn.grid(row=grid_info["row"], column=grid_info["column"], sticky=E)
SquadInfoBttn()
MainWindow.mainloop()

Trying to change label using entry box and button

I'm trying to make a label that will change when I enter text into the entry box and click the button.
I've tried doing some research but can't seem to find out how to do it .
from tkinter import *
master = Tk()
master.title("Part 3")
v = StringVar()
v.set("Please change me")
lb= Label(master, textvariable=v, fg="red",bg="black").grid(row=0,column=0)
ent= Entry(master, textvariable=v,).grid(row=1,column=2)
b1= Button(master, text="Click to change", fg="red",bg="black").grid(row=1,column=0)
to do so, you first need to define a callback that changes the value. (example below)
You should also use two Variables of type StringVar to store the different Values
from tkinter import *
master = Tk()
master.title("Part 3")
lText = StringVar()
lText.set("Please change me")
eText = StringVar()
def ChangeLabelText(event=None):
global lText
global eText
lText.set(eText.get())
Then, bind the callback to the button
lb = Label(master, textvariable=lText, fg="red",bg="black").grid(row=0,column=0)
ent = Entry(master, textvariable=eText).grid(row=1,column=2)
b1 = Button(master, text="Click to change", fg="red",bg="black", command=ChangeLabelText).grid(row=1,column=0)

Tkinter - How would I create buttons in a new window, which has been created by a function being called? Python 3

from tkinter import *
def begin():
root = Tk()
root.title("main window")
root.geometry("1920x1080")
return #How would a button be placed in this window made by this function?
root = Tk()
root.title("Start up page")
root.geometry("1920x1080")
BeginButton = Button(app, text = "Begin", command=begin, bg="green")
BeginButton.grid(column = 2, row = 2, sticky = W)
BeginButton.config(height = 10, width = 30 )
root.mainloop()
How would I create new buttons in the new window, if the new window is being made by, in this case a function known as "begin".
Any response would be much appreciated!
I believe what you want to do is to modify the root window rather than create a new one. Here is a minimal working example:
from tkinter import *
root = Tk()
class App:
def __init__(self):
root.title("Start up page")
root.geometry("1920x1080")
self.beginB = Button(root, text="Begin", command=self.begin,
bg="green", height=10, width=30)
self.beginB.grid(sticky = W)
def begin(self):
root.title("main window")
self.beginB.destroy()
del self.beginB
self.goB = Button(root, text='Go on', command=self.go_on,
bg='red')
self.goB.grid(sticky=E)
def go_on(self):
self.label = Label(root, text="you have continued")
self.label.grid(row=1, sticky=S)
App()
root.mainloop()
An advantage of defining a class is that you can make forward references. In your code, you had to define the begin function before you create the begin button. With a class, I could put it after init, which to me is a more natural order. It is ofter the case that the initialization code calls or binds more than one function.

Categories

Resources