tkinter page not disappeared, destroy() not working - python

i am using tkinter for python gui app development.
i want to disappear a page when user will sweep to new page.
i am just open a new object of new class, and want to disappear it by destroy() but destroy not works
code -
import reg as r
from tkinter import *
import tkinter as tk
LARGE_FONT = ("Verdana", 12)
class Main(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
label = tk.Label(self, text="Tech Eye", font=LARGE_FONT)
label.pack()
self.button2 = Button(self.parent, text="Admin Registration", command=self.reg).place(x=260, y=300)
self.button3 = Button(self.parent, text="Exit", command=self.destroy).place(x=220, y=350)
#this destroy also not working
def reg(self):
new = tk.Tk()
new.geometry("600x600")
new.title("Third Eye")
self.destroy()
st = r.Registration(new)
#r is the another python file what i imported and Registration is the class
st.mainloop()
if __name__ == '__main__':
root = tk.Tk()
root.geometry("600x600")
root.title("Third Eye")
run = Main(root)
root.mainloop()
what i can do now?

Related

TopLevel window disappears when using askopenfilename, from tkinter.filedialog

For my program I want the user to select a file, and I am using the tkinter.filedialog library to do this. However, when the askopenfilename dialog is opened, the TopLevelwindow disappears behind the main Tk() window.
How would I stop this from happening?
Here is the code that I have written so far:
from tkinter import *
from tkinter.filedialog import askopenfilename
class MainWin(Tk):
def __init__(self):
super(MainWin, self).__init__()
self.update()
pu = PopUp(self)
self.configure(width=500, height=300)
class PopUp(Toplevel):
def __init__(self, master):
super(PopUp, self).__init__(master)
def entry_set(entry, text):
entry.delete(0, 'end')
entry.insert(END, text)
item_file = StringVar()
item_entry = Entry(self, textvariable=item_file)
item_entry.place(x=80, y=60, height=20, width=300)
item_label = Label(self, text="item file: ", bg="gray74", relief="groove")
item_label.place(x=20, y=60, height=20, width=60)
item_button = Button(self, text="\uD83D\uDCC2", relief="groove",
command=lambda: entry_set(item_entry, askopenfilename()))
item_button.place(x=380, y=60, height=20, width=20)
self.configure(width=460, height=180)
if __name__ == '__main__':
win = MainWin()
win.mainloop()
Edit:
I have realised that using the .grab_set() method works, and will make the
TopLevel() window appear back on top of the Tk() after the file is chosen.
However, this still means the window disappears behind the Tk() window whilst picking a file, I would still love to find a solution to this, even though this is now just a visual problem, not a functional one.
You can just make the Toplevel window a transient window, it will then be kept on top of its parent window:
class PopUp(Toplevel):
def __init__(self, master):
super(PopUp, self).__init__(master)
self.transient(master)

issues with closing a window in tkinter

To keep this as short as possible - In my program I start with Page1 and when I press a button I want to open Page2 and close Page1, I have managed to open Page2 but I cant close Page1, I have tried using .destroy() but it closes everything not just the page. I looked around some questions here on SO but couldn't find much in the same layout as my code so I wasnt sure how to apply it to mine. This is my first tkinter project so I am still getting to grips with it.
My code is;
class Page1:
def __init__(self,master):
self.master = master
#lots of labels and buttons
self.BTNNextPage = ttk.Button(master, text = "Proceed",
command = self.NextPage)
self.BTNNextPage.place(x=450, y=420)
def NextPage(self):
self.newWindow = tk.Toplevel(self.master)
self.app = Page2(self.newWindow)
self.master.destroy()
class Page2():
def __init__(self,master):
self.master = master
#tried Page1.destroy() here but Page1 has no attibute destroy
#more labels and buttons
def main():
widthpixels=690
heightpixels=500
root = tk.Tk()
root.resizable(width=False, height=False)
root.configure(background='black')
root.iconbitmap("Image")
root.wm_title("Title")
root.geometry('{}x{}'.format(widthpixels, heightpixels))
app = Page1(root)
root.mainloop()
if __name__ == "__main__":
main()
If you destroy root, it destroys all the widgets contained, including Page2. To destroy only page 1, one possibility is to make the page classes inherit from tk.Frame, so that they have a destroy method:
import tkinter as tk
from tkinter import ttk
class Page1(tk.Frame):
def __init__(self, master, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.pack(fill='both', expand=True) # display page 1
#lots of labels and buttons:
tk.Label(self, text='Page 1').place(relx=0.5, rely=0.5)
self.BTNNextPage = ttk.Button(self, text="Proceed", command=self.NextPage)
self.BTNNextPage.place(x=450, y=420)
def NextPage(self):
self.app = Page2(self.master) # create page 2
self.destroy() # remove page 1
class Page2(tk.Frame):
def __init__(self, master, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.pack(fill='both', expand=True) # display page 2
# create widgets on page 2
tk.Label(self, text='Page 2').pack()
tk.Button(self, text='Quit', command=self.master.destroy).pack(side='bottom')
def main():
widthpixels=690
heightpixels=500
root = tk.Tk()
root.resizable(width=False, height=False)
root.configure(background='black')
root.wm_title("Title")
root.geometry('{}x{}'.format(widthpixels, heightpixels))
app = Page1(root)
root.mainloop()
if __name__ == "__main__":
main()

import a python file that create a window when main window button clicks

I am creating 2 window in my program and i am using two class, since the code is complex, i separate it in 2 different python file. After i imported the second window file, how can i make sure it open without having this error which show in this picture
The original result should look like this after the new window button clicked:
Coding for Main Window:
from tkinter import *
import classGUIProgram
class Window(Tk):
def __init__(self, parent):
Tk.__init__(self, parent)
self.parent = parent
self.initialize()
def initialize(self):
self.geometry("600x400+30+30")
self.wButton = Button(self, text='newWindow', command = self.OnButtonClick)
self.wButton.pack()
def OnButtonClick(classGUIProgram):
classGUIProgram.top = Toplevel()
master = Tk()
b = classGUIProgram.HappyButton(master)
master.mainloop()
if __name__ == "__main__":
window = Window(None)
window.title("title")
window.mainloop()
Coding for Second Window:
from tkinter import *
class HappyButton:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.printButton = Button(frame, text="Print message", command=self.printMessage)
self.printButton.pack(side=LEFT)
self.quitButton = Button(frame, text="Quit", command= quit)
self.quitButton.pack(side=LEFT)
self.downloadHistoryCB=Checkbutton(frame, text="Download History")
self.downloadHistoryCB.pack(side=LEFT)
def printMessage(self):
print("Wow this actually worked!")
master = Tk()
b = HappyButton(master)
master.mainloop()
You're creating extra Tk windows. Here is an example of using Toplevel widgets and another file.
mainWindow.py
import tkinter as tk
import secondWindow as sW
class MainWindow(tk.Tk):
def __init__(self):
super().__init__()
self.title("Main Window")
self.geometry("600x400+30+30")
tk.Button(self, text = "New Window", command = self.new_window).pack()
tk.Button(self, text = "Close Window", command = self.close).pack()
self._second_window = None
def new_window(self):
# This prevents multiple clicks opening multiple windows
if self._second_window is not None:
return
self._second_window = sW.SubWindow(self)
def close(self):
# Destory the 2nd window and reset the value to None
if self._second_window is not None:
self._second_window.destroy()
self._second_window = None
if __name__ == '__main__':
window = MainWindow()
window.mainloop()
secondWindow.py
import tkinter as tk
class SubWindow(tk.Toplevel):
def __init__(self, master):
super().__init__(master)
self.title("Sub Window")
self.geometry("400x300+30+30")
# Change what happens when you click the X button
# This is done so changes also reflect in the main window class
self.protocol('WM_DELETE_WINDOW', master.close)
tk.Button(self, text = "Print", command = self.printMessage).pack()
def printMessage(self):
print("Wow this actually worked!")
When using another file be sure to not have any global code you don't want running. Your classes don't have to inherit from Tk and Toplevel, this is just an example. But you need to ensure you only ever have one instance of Tk otherwise you get the behaviour you encountered

Python how to show text in a tkinter application on a none-button

I'm extremely new to python and has started a small project to learn stuff. anyways, as it says in the title, how do I show text in a tkinter application without creating buttons? here's the code if you need it
import tkinter as tk
ulo = 1
hoho = 0
def lul():
global ulo
#ulo = ulo + 1
global hoho
hoho = hoho + ulo
print(hoho)
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.hi_there = tk.Button(self, fg="green")
self.hi_there["text"] = "Pressing buttons is fun,\n isn't it?"
self.hi_there["command"] = self.lel
self.hi_there.pack(side="top")
def lel(self):
lul()
root = tk.Tk()
app = Application(master=root)
app.mainloop()
There are couple options but using Labels are the most fitting one since Label's job is showing text/image.
The Label widget is a standard Tkinter widget used to display a text
or image on the screen. The label can only display text in a single
font, but the text may span more than one line.
def createWidgets(self):
self.lbl = tk.Label(self, text="Pressing buttons is fun, isn't it?")
self.hi_there = tk.Button(self, fg="green")
self.hi_there["text"] = "Let's press"
self.hi_there["command"] = self.lel
self.lbl.pack()
self.hi_there.pack(side="top")
You can use tkinter built-in Label widget to display text :
Here's the code:
from tkinter import *
root=Tk()
def showLabel():
myLabel=Label(root,text="Hello World")
myLabel.pack()
myButton=Button(root,text="Click here",command=showLabel)
myButton.pack()
root.mainloop()

Browsing not shown for Python GUI Tkinter

I have done a simple tkinter GUI, i wanted a browse button but it doesn't seem to appear
#!/usr/bin/env python
import Tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.quit_program()
def quit_program(self):
self.quitButton = tk.Button(self, text='Quit',
command=self.quit)
self.quitButton.grid()
def browse_file(self):
self.browseButton = tk.Button(self, text='Browse',
command=tkFileDialog.askopenfilename(parent=root,title='Open file to encrypt'))
self.browseButton.grid()
app = Application()
app.master.title('Sample application')
app.mainloop()
#!/usr/bin/env python
import Tkinter as tk
import tkFileDialog
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.quit_program()
self.browse_file()
self.file_opt = options = {}
options['defaultextension'] = '.txt'
options['filetypes'] = [('musicfiles', '.mp3'),('vediofiles', '.mp4')]
options['parent'] = self
options['title'] = 'This is a title'
def quit_program(self):
self.quitButton = tk.Button(self, text='Quit',
command=self.quit)
self.quitButton.grid()
def browse_file(self):
self.browseButton = tk.Button(self, text='Browse',command=self.askopenfile)
self.browseButton.grid()
def askopenfile(self):
return tkFileDialog.askopenfile(**self.file_opt )
app = Application()
app.master.title('Sample application')
app.mainloop()
Three mistakes in your code
What is tkFileDialog? Have you imported it? Import it by adding import tkFileDialog at the top of your file
What is root? Change root to self.
The command argument in the tk.Button is not meant to be used the way you have. You should not call the method in the command argument. You should specify a method to be called when the button is clicked. In your example, you are telling tkinter, to call the value returned by tkFileDialog.askopenfilename() instead of calling tkFileDialog.askopenfilename. So replace it with another method or use a lambda.
command=lambda : tkFileDialog.askopenfilename(parent=root,title='Open file to encrypt')

Categories