how can I create a cancel button in tkinter - python

Hi I'm new in tkinter and I was trying to code a window with a button creating a new window. I want to add a new button (for cancel) in new window. I cant add a cancel button in my second window.
here is my code:
from tkinter import *
from tkinter.ttk import *
master = Tk()
master.geometry("200x200")
def openNewWindow():
newWindow = Toplevel(master)
newWindow.title("New Window")
newWindow.geometry("200x200")
Label(newWindow,
text="This is a new window").pack()
label = Label(master,
text="This is the main window")
label.pack(pady=10)
btn = Button(master,
text="Click to open a new window",
command=openNewWindow)
btn.pack(pady=10)
mainloop()

Insert the following code lines at the end of openNewWindow function to destroy newWindow.
clo = Button(
newWindow, text = "Close new window", command = newWindow.destroy)
clo.pack(pady = 10)
If you need to perform some action before destroying newWindow then create a function.
def closer():
# do something
newWindow.destroy()
And change openNewWindow close button like this.
clo = Button(
newWindow, text = "Close new window", command = closer)
clo.pack(pady = 10)

Related

Checkbutton does not work on a nested tkinter window

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.

Tkinter how to use a button to hide current window and open new one

Im trying to use a tkinter button that when clicked opens another window and hides the current one with the button inside.
def game():
window = tk.Toplevel()
window.geometry("1280x720")
root = tk.Tk()
root.title('testgame')
root.resizable(False,False)
root.geometry("500x500")
pbutton = tk.Button(root, text='Play', width=25, command=game and root.withdraw).place(relx = 0.5,rely = 0.5, anchor = 'center')
root.mainloop()
You can try something like this:
import tkinter as tk
root = tk.Tk()
#In order to hide main window
root.withdraw()
tk.Label(root, text="Main Window").pack()
aWindow = tk.Toplevel(root)
def change_window():
#remove the other window entirely
aWindow.destroy()
#make root visible again
root.iconify()
root.deiconify()
tk.Button(aWindow, text="This is aWindow", command=change_window).pack()
root.mainloop()

Opening a Child Window When Clicking An Entry Window Is Not Getting Closed

a. Have a simple program, where in I wanted to open a child window from main window.
b. I have an open button, when I click that it opens a new window and when I press the close button in the child window it closes the child window.
c. Similarly I wanted the same option in the entry widget.
d. When I click the entry widget to enter something, this should pop-up a child window giving some user tips.
d. This function opens the child window as expected, but when I click the close button in the child process its not getting closed.
#!/tools/bin/python
from Tkinter import *
#import Tkinter as tk
class MyFirstGUI:
cw = None
def __init__(self, master):
self.master = master
master.title("A simple GUI")
self.label = Label(master, text="This is our first GUI!")
self.label.pack()
self.greet_button = Button(master, text="Greet", command=self.greet)
self.greet_button.pack()
self.close_button = Button(master, text="Close", command=quit)
self.close_button.pack()
self.open_button = Button(master, text="Open", command=self.create_window)
self.open_button.pack()
self.scae1 = Entry(root, width=43, bg="yellow")
self.scae1.delete(0, END)
self.scae1.insert(0, 'Enter The World')
self.scae1.bind('<FocusIn>', self.scae1_entry_click)
self.scae1.pack()
def greet(self):
print("Greetings!")
def create_window(self):
self.cw = Toplevel()
self.cw.wm_title("A New Window")
self.l = Label(self.cw, text="This is window")
self.l.pack()
self.cw_text = Text(self.cw)
self.cw_text.insert('1.0', "Please Enter the Following")
self.cw_text.pack()
self.close_button = Button(self.cw, text="Close", command=self.close_window)
self.close_button.pack()
def close_window(self):
if self.cw:
try: self.cw.destroy()
except (): pass # fill in the error here
self.cw = None
def scae1_entry_click(self,event):
if (self.scae1):
if self.scae1.get() == 'Enter The World':
self.scae1.delete(0, "end") # delete all the text in the entry
self.scae1.insert(0, '') #Insert blank for user input
self.scae1.configure(bg="white")
self.create_window()
root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()
It would be great if anyone gives some suggestions or comments why this child window is not getting closed when you open it from the entry widget.
Thanks in Adv,
Vimo
Wow that was a very interesting error. But you have a loop in your logic. So what is happening is, if you close your toplevel-Window the Entry-Widget get automaticly the focus. If this happens your binding is triggering again. So just change this line:
self.scae1.bind('<FocusIn>', self.scae1_entry_click)
to this:
self.scae1.bind('<Button-1>', self.scae1_entry_click)
Or make sure your Entry loses the focus.

New windows in tkinter

I have a bit of difficulty with the code below. Basically, I want the code to, when I press the Enter button, to open the window2 but also close window1 simultaneously so that there is only one window and not two of them.
The code is...
from tkinter import *
def window1():
window = Tk()
window.title("Welcome")
f = Frame()
f.pack()
label1 = Label(window, text = "Welcome to the random window")
label1.pack()
button1 = Button(window, text = "Enter...", command = window2)
button1.pack()
def window2():
screen = Tk()
screen.title("Pop-Up!")
fr = Frame()
fr.pack()
label2 = Label(screen, text = "This is a pop-up screen!")
label2.pack()
button2 = Button(screen, text = "Return", command = window1)
button2.pack()
window1()
This is "Bad" because you're using two instances of Tk. Try instead using TopLevels.
import tkinter as tk
def window1():
window = tk.Toplevel(root)
window.title("Welcome")
# etc etc ...
tk.Button(window,text="Enter...",command=lambda: window2(window)).pack()
def window2(old_window):
old_window.destroy()
# window2 stuff
root = tk.Tk()
root.iconify() # to minimize it, since we're just using Toplevels on top of it
window1()
root.mainloop()
When you are using the Tk() function, you are creating a new instance of the Tcl/tkinter interpreter. Instead use Toplevel() which will make a new window in the current interpreter.

make a button open only one window at a time (enable a button by closing a Toplevel window)

I want NewWinButton to create only one new window at a time, which means if
if NewWin.winfo_exists() == 1:
NewWinButton.config(state='disabled')
else:
NewWinButton.config(state='normal')
I can make this work if I add a button to the new window (QuitButton in this example):
import tkinter as tk
root = tk.Tk()
root.title('Main Window')
root.geometry('400x400')
def get_new_win():
NewWin = tk.Toplevel(root)
NewWin.title('New Window')
NewWin.geometry('300x300')
NewWinButton.config(state='disable')
def quit_win():
NewWin.destroy()
NewWinButton.config(state='normal')
QuitButton = tk.Button(NewWin,text='Quit', command=quit_win).pack()
NewWinButton = tk.Button(root,text='New Window', get_new_win).pack()
root.mainloop()
This works if and only if I use QuitButton to close the new window; however, if I use the close button in the new window, then the NewWinButton will remain 'disabled'.
Can anyone tell me how to fix this?
Use NewWin.protocol("WM_DELETE_WINDOW", quit_win) to assign function quit_win to the close button.
import tkinter as tk
root = tk.Tk()
root.title('Main Window')
root.geometry('400x400')
def get_new_win():
NewWin = tk.Toplevel(root)
NewWin.title('New Window')
NewWin.geometry('300x300')
NewWinButton.config(state='disable')
def quit_win():
NewWin.destroy()
NewWinButton.config(state='normal')
QuitButton = tk.Button(NewWin, text='Quit', command=quit_win)
QuitButton.pack()
NewWin.protocol("WM_DELETE_WINDOW", quit_win)
NewWinButton = tk.Button(root, text='New Window', command=get_new_win)
NewWinButton.pack()
root.mainloop()
BTW:
The pack() method returns None, not a button instance:
NewWinButton = tk.Button(...).pack()
use this:
NewWinButton = tk.Button(...)
NewWinButton.pack()

Categories

Resources