Connecting the same GUI to two or more python files - python

i am building a small project which involves 4 python files which have their separate functionalities. There is however, a main.py file which uses all the others by importing them.
Now, i have to build a GUI for this project, which i am building within the main.py file. My problem is that some of the other files have functions which print on the console, when the whole project is run, i want those functions to print on the GUI instead. So, how do i print the text from the other file in a Text field created in the main file.
main.py
import second as s
from tkinter import *
def a():
field.insert(END, "Hello this is main!")
root = Tk()
field = Text(root, width=70, height=5, bd=5, relief=FLAT)
button1 = Button(root, width=20, text='Button-1', command=a)
button2 = Button(root, width=20, text='Button-2', command=s.go)
root.mainloop()
second.py
def go():
print("I want this to be printed on the GUI!")
#... and a bunch of other functions...
I just want that when user presses the button-2, then the function go() prints the text on the field

I consider it the best way to try add field as an argument of function go.
Here is my code:
main.py
import second as s
from tkinter import *
def a(field):
field.insert(END, "Hello this is main!\n")
root = Tk()
field = Text(root, width=70, height=5, bd=5, relief=FLAT)
button1 = Button(root, width=20, text='Button-1', command=lambda : a(field))
button2 = Button(root, width=20, text='Button-2', command=lambda : s.go(field))
#to display widgets with pack
field.pack()
button1.pack()
button2.pack()
root.mainloop()
second.py
from tkinter import *
def go(field):
field.insert(END, "I want this to be printed on the GUI!\n")
print("I want this to be printed on the GUI!")
#something you want
The screenshot of effect of running:)

Related

how to get an output message from tkinter?

I'm trying to make a quiz app and I have written the following code which is incomplete I am trying to get an output message from the app which gives the answer which the student has written it seems funny but i will do some more stuff on it too. the output I want should be something like this:
the client enters 12
the app shows another box which says your answer is 12
but in this example it is being done for a single answer and it should be performable for more questions too.
import tkinter as tk
from tkinter import *
import math
import random
window=tk.Tk()
def question():
window=tk.Tk()
q1=tk.Label(window, text="enter your question").grid(row=1, column=1)
e1=tk.Entry(window, text="the number of your answer ").grid(row=2, column=1)
b1=tk.Button(window, text="exit", command=window.destroy).grid(row=3, column=1)
window.mainloop()
after your helps I have changed my code to this but still have prolems getting a message box or something like that. the updated code is as follows. now the problem is that as soon as I run the code the empty message box opens and does not wait for me to enter some value into the entry
def question():
window=tk.Tk()
q1=tk.Label(window, text="enter your question")
e1=tk.Entry(window, text="the number of your answer ")
b1=tk.Button(window, text="exit", command=window.destroy)
q1.grid(row=1, column=1)
e1.grid(row=2, column=1)
b1.grid(row=3, column=1)
e1_num=e1.get()
while e1_num==None:
pass
else:
messagebox.showinfo(e1_num)
mainloop()
You could use e1.insert('0', 'subject') to insert something into the entry. You can also replace 'subject' with a variable. To delete the contents of the entry you can use e1.delete(0,END)
You can get the information from the Entry (e1) and store in it a variable like so: e1_num = e1.get()
I hope this helps you :D
Solution to your problem:
from tkinter import *
import tkinter as tk
def question():
window=tk.Tk()
window.geometry('200x125')
window.title('Test')
q1=tk.Label(window, text="Enter your question")
e1=tk.Entry(window)
e2=tk.Entry(window)
b1=tk.Button(window, text="Exit", command=window.destroy)
def Enter():
e1_num = e1.get()
e2.insert('0', e1_num)
q1.pack()
e1.pack()
b2=Button(window, text='Enter', command=Enter)
b2.pack()
e2.pack()
b1.pack()
window.mainloop()
question()
What it will look like:

python entry widget and get method

Is there any way to put the textvariable in another variable and not have to use the ".get()"? I've been doing a lot of sifting thorugh tutorials and articles for what I realize is a very small issue but I'm probably misunderstanding something pretty key so i'm hoping someone can help me develop some intuition for the entry widget and .get() method.
Below is part of a script that I've been working on where I want to take the text entered in the entry box and use it later. I can use it if I use search_word.get(), but I don't why I can't do something like New_variable=search_word.get() so that from that point on I can just use "New_variable".
import tkinter as tk
from tkinter import *
from tkinter import ttk
Text_input_window = Tk()
Text_input_window.geometry('600x350+100+200')
Text_input_window.title("Test")
label_1=ttk.Label(Text_input_window, text="Enter word to search:", background="black", foreground="white")
label_1.grid(row=1, column=0, sticky=W)
search_word=StringVar()
entry_1=ttk.Entry(Text_input_window,textvariable=search_word, width=40, background="white")
entry_1.grid(row=2, column=0, sticky=W)
New_variable=StringVar()
New_variable=search_word.get()
def click():
print(New_variable)
print(search_word.get())
Text_input_window.destroy()
btn_1=ttk.Button(Text_input_window, text="submit", width=10, command=click)
btn_1.grid(row=3, column=0, sticky=W)
Text_input_window.mainloop()
Problem is not .get() but how all GUIs works.
mainloop() starts program so new_variable = search_word.get() is executed before you even see window - so it tries to get text before you put text in Entry.
You have to do it inside click() which is executed after you put text in entry and click button.
import tkinter as tk
# --- functions ---
def click():
global new_variable # inform function to use external/global variable instead of creating local one
#new_variable = entry.get() # you can get it directly from `Entry` without StringVar()
new_variable = search_word.get()
root.destroy()
# --- main ---
new_variable = '' # create global variable with default value
root = tk.Tk()
search_word = tk.StringVar()
entry = tk.Entry(root, textvariable=search_word)
entry.pack()
btn = tk.Button(root, text="submit", command=click)
btn.pack()
root.mainloop() # start program
# --- after closing window ---
print('new_variable:', new_variable)
print('search_word:', search_word.get()) # it seems it still exists
# print('entry:', entry.get()) # `Entry` doesn't exists after closing window so it gives error
Is there any way to put the textvariable in another variable and not have to use the ".get()"?
No, there is not. Tkinter variables are objects, not values. Anytime you want to use a value from a tkinter variable (StringVar, IntVar, etc) you must call the get method.

Python Script not responding

(I am a total beginner regarding programming)
I have written a python GUI to run batch files that can activate different Gamemodes in CSGO on a local Steam server. When I run the script everything works, but after I execute a command, the Programm does not respond anymore.
import tkinter as tk
import subprocess
def startA():
subprocess.call([r'D:\CSGO_server\Arms_race.bat'])
def startCa():
subprocess.call([r'D:\CSGO_server\Casual.bat'])
def startCo():
subprocess.call([r'D:\CSGO_server\Competitive.bat'])
def startDea():
subprocess.call([r'D:\CSGO_server\Deathmatch.bat'])
def startDem():
subprocess.call([r'D:\CSGO_server\Demolition.bat'])
def startQ():
subprocess.call([r'D:\CSGO_server\Quit.bat'])
root = tk.Tk()
root.title("Settings")
frame = tk.Canvas(root)
frame.pack()
Armsrace = tk.Button(frame,
text="Arms_race",
fg="red",
command=startA)
Armsrace.pack(side=tk.BOTTOM)
Casual = tk.Button(frame,
text="Casual",
fg="red",
command=startCa)
Casual.pack(side=tk.BOTTOM)
Competitive = tk.Button(frame,
text="Competitive",
fg="red",
command=startCo)
Competitive.pack(side=tk.BOTTOM)
Deathmatch = tk.Button(frame,
text="Deathmatch",
fg="red",
command=startDea)
Deathmatch.pack(side=tk.BOTTOM)
Demolition = tk.Button(frame,
text="Demolition",
fg="red",
command=startDem)
Demolition.pack(side=tk.BOTTOM)
Stop = tk.Button(frame,
text="Stop Server",
fg="red",
command=startQ)
Stop.pack(side=tk.BOTTOM)
root.mainloop()
Did I just fotget a loop?(but I have already a loop there, so how would I have to do this then?)
Or is it something completly diffrent?
Thanks in advance
(also sorry for not putting the code as sample code)
did you check your directory if there exists your files or not?

Placing Tkinter Frame in another Frame

I am trying to experiment and get the button to only display the label when the button is clicked instead it is opening up another GUI window. The main frame is called secret message. Within this when i click onto the button it should then replace the empty place with the label in row=2.
Could someone explain to me how i can raise the label rather than just opening up a new window. All code is functional but i want another way around this, i am new to python.
from tkinter import *
def topLevel():
top=Toplevel()
top.geometry("300x200")
root=Tk()
root.title("Secret Message")
button1 = Button(text="Push this button to see hidden message!", width =60, command=topLevel)
button1.grid(row=1, column=0)
label1 = Label(width=50, height=10, background="WHITE", text= "There is no secret!")
label1.grid(row=2, column=0)
root.mainloop()
You question title has nothing to do with your question.
To update the geometry of your label you simple need to tell the function where you want the label on the container you set up your label in. In this case you do not define the container so the widgets default to the root window.
Here is a working example that will update the label geometry when you press the button.
from tkinter import *
root=Tk()
root.title("Secret Message")
def grid_label():
label1.config(text="There is no secret!")
Button(root, text="Push this button to see hidden message!", width=60, command=grid_label).grid(row=1, column=0)
label1 = Label(root, width=50, height=10, background="WHITE")
label1.grid(row=2, column=0)
root.mainloop()

Preventing circular import example

Lets say I have two python files. Both with an GUI. First is "Main" second is "Calculator". From Main I will start Calculator. So I have to import calculator. In Calculator I will do a calculation. Lets keep I easy an say 1+1=2. Now I want to "send" this Result to an Text in Main.
How do I do that without an circular import? I cant find an good tutorial/example for that!
My code so far:
Main:
from tkinter import *
import Test_2
window = Tk()
window.title("First Window")
def start():
Test_2.start_second()
Input1 = Entry(window)
Input1.grid(row=0,column=0, padx=10, pady=5)
Start = Button(window,text="Start", command=start)
Start.grid(row=1,column=0, padx=10, pady=5)
window.mainloop()
Second:
from tkinter import *
def start_second():
window2 = Tk()
window2.title("Second Window")
def send():
x = Input.get()
Input2 = Entry(window2)
Input2.grid(row=0,column=0, padx=10, pady=5)
Send = Button(window2,text="Send", command=send)
Send.grid(row=1,column=0, padx=10, pady=5)
window2.mainloop()
This code does exactly what you asked for (as opposed to what I suggested in the comment; but anyway, you either get a value from a module function or you send a reference for it to alter)
I tried to follow your structure.
Basically it is a matter of sending the parent window and the first entry as parameters to the second window creation function. Don't call mainloop two times, just once in the end, and use Toplevel for all other windows after the main Tk one. This is not to say that I like the use of an inner function and of the lambda, for readability, but lambdas are necessary in tkinter everytime you want to send parameters to a command callback, otherwise it will get called right way in command definition.
tkinter_w1.py (your main.py)
from tkinter import Tk, ttk
import tkinter as tk
from tkinter_w2 import open_window_2
root = Tk()
entry1 = ttk.Entry(root)
button1 = ttk.Button(root, text='Open Window 2',
command=lambda parent=root, entry=entry1:open_window_2(parent, entry))
entry1.pack()
button1.pack()
root.mainloop()
tkinter_w2.py (your Test_2.py)
from tkinter import Tk, ttk, Toplevel
import tkinter as tk
def open_window_2(parent, entry):
def send():
entry.delete(0,tk.END)
entry.insert(0,entry2.get())
window2 = Toplevel(parent)
entry2 = ttk.Entry(window2)
button2 = ttk.Button(window2, text='Send', command=send)
entry2.pack()
button2.pack()

Categories

Resources