Open window on button click, close current window? - python

I have been searching for a solution for this issue, but I can't seem to find a viable answer.
I have the following code to open another tkinter script on button click:
# Program to Open on Button Click
def tkinter1():
ret = os.system('python C:\filepath\new_script.py"')
if ret:
# record updated, reload data
treeview_preview()
b1 = Button(master, text="New Window", command=tkinter1)
My problem I am facing is that I want the current window to close on the button click and only keep the new window open.
I know it is possible. I have this instance with many different windows and I seem to be stuck.
The unfortunate thing is that I have an entire different script for different parts of the beta software and the only way I could successfully run all of them is to access them as stated above.
I tried using the if ret: exit() command at the end with the same result. I have windows opening over and over again.
It seems simple, but I haven't been programming tkinter script for too long.(I still have a lot to learn)
All help is appreciated.

You can use master.withdraw(). I
made your code runnable with a few lines. Ok lets say your fixed main code is this:
import tkinter as tk
from tkinter import *
from seccond import *
from multiprocessing import Process
import os
def main():
master = tk.Tk()
# Program to Open on Button Click
def tkinter1():
master.withdraw()
master.destroy()
ret = Process(target=treeview_preview())
ret.start()
#if ret:
# # record updated, reload data
# treeview_preview()
#commented out bc i don't know what it is
b1 = Button(master, text="New Window", command=tkinter1)
b1.pack()
master.mainloop()
if __name__ == '__main__':
main()
the secondary code name seccond.py in the same folder as the main code is called as an external function but also as a separate process.
import tkinter as tk
def treeview_preview():
root = tk.Tk()
S = tk.Scrollbar(root)
T = tk.Text(root, height=4, width=50)
S.pack(side=tk.RIGHT, fill=tk.Y)
T.pack(side=tk.LEFT, fill=tk.Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
quote = """this is the seccond window."""
T.insert(tk.END, quote)
tk.mainloop()
The code will remove the window but not the terminal box as it will use it for the second script.

Related

tkinter python program structure

I'm new to python programming, and I have a bit of trouble with the program structure:
When I make my GUI in the main python part then the code works:
import tkinter as tk
root = tk.Tk()
root.overrideredirect(True)
root.geometry("800x480")
def cb_Gebruiker():
btnUser["text"]= "changed"
btnUser = tk.Button(root, text="User",command = cb_Gebruiker)
btnUser.place(x=1,y=1,width="300",height="73")
root.mainloop()
When I make my GUI in a function, the btn variable is local, so this doesn't work
def MakeBtn():
btnUser = tk.Button(root, text="User",command = cb_Gebruiker)
btnUser.place(x=1,y=1,width="300",height="73")
def cb_Gebruiker():
btnUser["text"]= "changed"
MakeBtn()
root.mainloop()
Now I have a program that's rather large and I want my GUI in a separate file, but then I can't access my GUI components...
And I can't seem to be able to find a tutorial on how to structure a program (python has to many possibilities: script, module, object oriented,..)
How do I solve this?
You will need a lambda to delay the call to the command with a parameter.
def MakeBtn():
btnUser = tk.Button(root, text="User", command = lambda: cb_Gebruiker(btnUser))
btnUser.place(x=1, y=1, width="300", height="73")
def cb_Gebruiker(btnUser):
btnUser["text"] = "changed"
MakeBtn()
root.mainloop()

Using Python, how do you call a tkinter GUI from another GUI?

I created a couple of GUIs using tkinter. But now I am interested in combining them into one caller GUI. So the caller GUI would have buttons that, when clicked, would open the other GUIs. However, I cannot get it to work. I've done the imports correctly (I think), edited the main functions in the subGUIs, and added the command=GUI.main in my buttons. I get it to load but I get errors about missing files...but when I run a GUI by itself it works fine.
In my research, I read that there can only be one mainloop in a Tkinter program. Basically, I cannot use a Tkinter GUI to call another Tkinter GUI. Do you know what I can do different, for instance, can I create the caller GUI using wxPython and have it call all other GUIs that use Tkinter?
Thank you!
You can't "call" another GUI. If this other GUI creates its own root window and calls mainloop(), your only reasonable option is to spawn a new process. That's a simple solution that requires little work. The two GUIs will be completely independent of each other.
If you have control over the code in both GUIs and you want them to work together, you can make the base class of your GUI a frame rather than a root window, and then you can create as many windows as you want with as many GUIs as you want.
For example, let's start with a simple GUI. Copy the following and put it in a file named GUI1.py:
import tkinter as tk
class GUI(tk.Frame):
def __init__(self, window):
tk.Frame.__init__(self)
label = tk.Label(self, text="Hello from %s" % __file__)
label.pack(padx=20, pady=20)
if __name__ == "__main__":
root = tk.Tk()
gui = GUI(root)
gui.pack(fill="both", expand=True)
tk.mainloop()
You can run that GUI normally with something like python GUI1.py.
Now, make an exact copy of that file and name it GUI2.py. You can also run it in the same manner: python GUI2.py
If you want to make a single program that has both, you can create a third file that looks like this:
import tkinter as tk
import GUI1
import GUI2
# the first gui owns the root window
win1 = tk.Tk()
gui1 = GUI1.GUI(win1)
gui1.pack(fill="both", expand=True)
# the second GUI is in a Toplevel
win2 = tk.Toplevel(win1)
gui2 = GUI2.GUI(win2)
gui2.pack(fill="both", expand=True)
tk.mainloop()
Depending on your OS and window manager, one window might be right on top of the other, so you might need to move it to see both.
Thank you for the ideas. At first, your code wouldn't print the text on the toplevel window. So I edited it a little and it worked! Thank you. GUI1 and GUI2 look like:
import tkinter as tk
def GUI1(Frame):
label = tk.Label(Frame, text="Hello from %s" % __file__)
label.pack(padx=20, pady=20)
return
if __name__ == "__main__":
root = tk.Tk()
GUI1(root)
root.mainloop()
And then the caller looks like this:
from tkinter import *
import GUI1
import GUI2
def call_GUI1():
win1 = Toplevel(root)
GUI1.GUI1(win1)
return
def call_GUI2():
win2 = Toplevel(root)
GUI2.GUI2(win2)
return
# the first gui owns the root window
if __name__ == "__main__":
root = Tk()
root.title('Caller GUI')
root.minsize(720, 600)
button_1 = Button(root, text='Call GUI1', width='20', height='20', command=call_GUI1)
button_1.pack()
button_2 = Button(root, text='Call GUI2', width='20', height='20', command=call_GUI2)
button_2.pack()
root.mainloop()

Tkinter: messagebox doesn`t work right. (get two windows)

I am using python 3.
If I opan an error messagebox, i get two frames, one is emty and one is the error-window. That is my code:
from tkinter import messagebox
messagebox.showwarning('warning', 'warning')
Everything works correctly in your example. The empty window is the main window of Tk. It is always open when you start any Tk program. You can minimize it if you want, but closing it terminates the main loop.
Try this:
root = tkinter.Tk()
root.withdraw()
messagebox.showwarning('warning', 'warning')
Thank you DYZ,
in my code is no main window, (eg.: main = Tk() ... main.mainloop), because of that the warning massage create one. I could solve the problem by create one and minimize it. at the end of massagebox I destroyed it to continue in code.
from tkinter import *
from tkinter import messagebox
main = Tk()
main.geometry("500x400+300+300")
def message():
main.geometry("0x0")
messagebox.showwarning("Say Hello", "Hello World")
main.destroy()
B1 = Button(main, text = "Start Dialog",fg="dark green", command = message)
B1.pack()
main.mainloop()
print("finish dialog")

Tkinter threading and return to text widget

I've read some post on stack overflow,Issues intercepting subprocess output in real time, Redirect command line results to a tkinter GUI, i know i have to use threading and queue in tkinter, but I am still can't do the same thing because I am a beginner in program,please help.
The goal: When press a button, getting the 'top' command output and realtime display in tkinter text widget
The issue: I've tried to follow the code, but still cannot get the output, but I have not idea how to make it work.
from tkinter import *
import tkinter as tk
import subprocess
from threading import Thread
from queue import Queue
window = tk.Tk()
window.title('realtime')
window.geometry('800x400')
text = tk.Text(window)
text.pack()
button = tk.Button(window, text= 'Press')
button.pack()
window.mainloop()
This is only the gui outlook, please help
top refreshes itself now and then and I'm guessing that's the behavior you want to capture with threading and whatnot. However in this case it would be much easier to ask top to only run once, and have tkinter do the timing and refreshing:
import tkinter as tk
from sh import top
def update_text():
text.delete(0.0, tk.END)
text.insert(0.0, top('-b', n=1))
window.after(1000, update_text) # call this function again in 1 second
window = tk.Tk()
window.title('realtime')
window.geometry('800x400')
text = tk.Text(window)
text.pack()
button = tk.Button(window, text= 'Press', command=update_text)
button.pack()
window.mainloop()
You may need to install sh to run top like I did, or use subprocess.check_output if you want.
text.insert(0.0, subprocess.check_output(['top', '-b', '-n 1']))

Creating a sub-process opens unwanted window

I'm currently developing a Windows application that requires the use of an .exe file I've created (called kill_game.exe in the below example). This .exe file accepts serialized objects as arguments. I call this .exe file using subprocess.Popen. When I do so, an exact copy of my current window opens and my .exe file won't run until I close the 2nd window myself. I'm completely stumped as to why it happens. I'd like the .exe file to run without the 2nd GUI opening itself. I tried to switch to multiprocessing as it exists in this example on SO, but that didn't work either.
Below, I'll post a simplified version (my original version is 300+ lines) of my code that illustrates the GUI and the function that is used to open the .exe file. I'll also post pictures of what happens when I press the button.
from tkinter import *
from tkinter import Tk
import subprocess
root = Tk()
sizex = sizey = 500
posx = posy = 100
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
myframe = Frame(root, relief=GROOVE, width=500, height=500, bd=1)
myframe.place(x=0, y=0)
canvas = Canvas(myframe)
frame = Frame(canvas)
canvas.pack(side="left")
canvas.create_window((0, 0), window=frame, anchor='nw')
button = Button(frame, text="Hello World")
button.grid(row=0, column=2)
games_to_stop = []
button.bind("<Button>",
lambda event, game_list=games_to_stop: some_function(game_list))
def some_function(game_list):
#This function is the function of interest, which is bound to my "Hello
#World" Button
child_script = r"C:\Users\Willy\AddictKiller\dist\kill_game.exe"
subprocess.Popen([child_script, game_list])
root.mainloop()
This is the GUI before the button is pressed:
This is the GUI and the 2nd GUI (which for some reason looks the the GUI of my non-simplified code) after the button is pressed:
I had a similar problem where when I run my program duplicates of my main Tkinter window would open and the function wouldn't run until I close all the duplicates.
you fix this by putting the part where the tkiner window is being created behind an if statement to make sure you only create a window in the main window as such
if __name__ == "__main__":
root = Tk()

Categories

Resources