how to get an output message from tkinter? - python

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:

Related

I am trying to have my "multible label widget" as well as my "creating buttons" but when when i get one to work the other does not

Here is the code that i have scripted i know it looks bad i am a total noob at this but i really need help. I want my GUI to show the "welcome" and "this gui was written by..." message at the bottom and then add the button functions that i am later going to intergrate with a api.
from cProfile import label
from tkinter import *
root = Tk()
def create_label():
# creating multible label widgets
myLabel1= Label(root,text="Welcome")
myLabel2= Label(root,text=" ")
myLabel3= Label(root,text=" ")
myLabel4= Label(root,text=" ")
myLabel5= Label(root,text="This Gui was written by Seha")
# Showing it on the screen and putting it in rows and columns
myLabel1.grid(row=0, column=10)
myLabel2.grid(row=1, column=10)
myLabel4.grid(row=2, column=10)
myLabel3.grid(row=3, column=10)
myLabel5.grid(row=4, column=10)
create_label.pack()
def create_button():
# Creating buttons
myButton= Button(root, text="Click on this button to check floor price for a specific collection: ",command=label)
myButton2= Button(root, text="Click on this button to check the 24h volume for a specific collection:", command=label)
myButton.pack()
myButton2.pack()
root.mainloop()
This is what my code looks like and i screenshotted what the gui shows
[1]: https://i.stack.imgur.com/jJnxu.png

subroot window editing - tkinter

I'm sure this is going to amount to my misunderstanding of what I'm calling. So I'm trying to make edits to a second window but I don't know that I'm doing it right as it doesn't appear to change. Under def open_win() I created a second window registration(which is supposed to be the equivalent of root). I got the second window to take the Screen position/size but for some reason it wont add the label/entry
from tkinter import *
from functools import partial
#outputs to IDLE
def validateLogin(username, password):
print("username entered :", username.get())
print("password entered :", password.get())
return
#centering Registration page
def open_win():
registration=Toplevel(root)
registration.title("Registration Page")
window_width=600
window_height=400
screen_width =registration.winfo_screenwidth()
screen_height =registration.winfo_screenheight()
center_x=int(screen_width/2-window_width/2)
center_y=int(screen_height/2-window_height/2)
registration.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
#registration label and text entry box
usernameLabel=Label(registration, text="User Name").grid(row=0, column=1)
username=StringVar()
usernameEntry=Entry(registration, textvariable =UserName).grid(row=0, column=2)
#Root Window
root=Tk()
root.title('Sign in Page')
#centering window
window_width=600
window_height=400
screen_width =root.winfo_screenwidth()
screen_height =root.winfo_screenheight()
center_x=int(screen_width/2-window_width/2)
center_y=int(screen_height/2-window_height/2)
root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
#username label and text entry box
usernameLabel=Label(root, text="User Name").grid(row=0, column=1)
username=StringVar()
usernameEntry=Entry(root, textvariable=username).grid(row=0, column=2)
#password label and password entry box
passwordLabel=Label(root,text="Password").grid(row=1, column=1)
password=StringVar()
passwordEntry=Entry(root, textvariable=password, show='*').grid(row=1, column=2)
validateLogin=partial(validateLogin, username, password)
#login button
loginButton=Button(root, text="Login", command=validateLogin).grid(row=4, column=1)
SignUpButton=Button(root, text="Sign up", command=open_win).grid(row=4, column=2)
#registration label and text entry box
usernameLabel=Label(registration, text="User Name").grid(row=0, column=1)
username=StringVar()
usernameEntry=Entry(registration, textvariable =UserName).grid(row=0, column=2)
root.mainloop()
Your main issue with not being able to work with the 2nd window is basically a issue of namespace. Your registration variable is stored in the local namespace of the function. If you want to edit it from outside the function like you attempt to do then you need your variable to be in the global namespace.
Because you appear to try and write the same label and entry field a couple of times to the registration top window then I suspect you do not actually need to edit it from outside the function but need to edit it when you created the window.
I have cleaned up your code a little and condensed it to make it a little easier to read.
You should first import tkinter ask tk instead of importing *. This will help prevent any issue with overwriting imports down the road and it makes it a little easier to ID what is referencing a tk widget or some other function.
You use 2 different naming conventions in your code. Chose one and stick with that. It will improve readability. I recommend following PEP8 guidelines.
Items that are not going to be changed later do not need to have variables assigned to them so you can clean up your code a bit there also.
You do not need to go the extra mile to use StringVar here. We can simply pull directly from the entry field as long as the geometry manager (ie grid()) is assigned on a new line so you can still access the variable reference for the entry field.
I am not sure what you were needing partial() for and I think you should use lambda instead in this situation.
If you have any questions let me know.
import tkinter as tk
def validate_login(username, password):
print("username entered :", username.get())
print("password entered :", password.get())
def open_win():
reg = tk.Toplevel(root)
reg.title("Registration Page")
reg.geometry(f'600x400+{int(reg.winfo_screenwidth()/2-600/2)}+{int(reg.winfo_screenheight()/2-400/2)}')
tk.Label(reg, text="User Name").grid(row=0, column=1)
r_un = tk.Entry(reg)
r_un.grid(row=0, column=2)
root = tk.Tk()
root.title('Sign in Page')
root.geometry(f'600x400+{int(root.winfo_screenwidth()/2-600/2)}+{int(root.winfo_screenheight()/2-400/2)}')
tk.Label(root, text="User Name").grid(row=0, column=1)
un = tk.Entry(root)
un.grid(row=0, column=2)
tk.Label(root, text="Password").grid(row=1, column=1)
pw = tk.Entry(root, show='*')
pw.grid(row=1, column=2)
tk.Button(root, text="Login", command=lambda u=un, p=pw: validate_login(u, p)).grid(row=4, column=1)
tk.Button(root, text="Sign up", command=open_win).grid(row=4, column=2)
root.mainloop()

Python: Reading from a spin box numbers and do following command of one

Good Morning/Evening,
I want to read a number from a spinbox, and if it is 2, it should print something. But my code does not work out. I've tried it with a slider instead of a spinbox and it worked out. But for me, it is really important to use a spinbox, so I hope somebody have an idea.
Code:
from tkinter import *
def a():
if spin.get()==2:
print("Hello World")
root = Tk()
root.geometry('300x100')
spin =Spinbox(root, from_=0, to=10,command=a)
button = Button(root, text='Enter')
button.pack(side=RIGHT)
spin.pack(side=RIGHT)
root.mainloop()
Adding to #coolCloud's answer I would suggest setting a textvariable for spinBox. So if the user changes it using the entry. It would automatically be updated.
Something like this:
from tkinter import *
def a(*event):
if text.get()=='2':
print("Hello World")
root = Tk()
root.geometry('300x100')
text = StringVar()
text.trace('w', a) # or give command=a in the button if you want it to call the event handler only when the button is pressed
spin =Spinbox(root, from_=0, to=10, textvariable=text)
button = Button(root, text='Enter')
button.pack(side=RIGHT)
spin.pack(side=RIGHT)
root.mainloop()

Python check if textbox is not filled

Currently I'm using Python tkinter to build a GUI that require user to enter the detail into the textbox(txt3)
How do I validate if the textbox is entered. If not entered, should
show message "please enter textbox" . If entered, it will go through
SaveInDB() to save in database.
def SaveInDB():
subID=(txt3.get())
if not (subID is None):
...my code here to save to db
else:
res = "Please enter textbox"
message.configure(text= res)`
txt3 = tk.Entry(window,width=20)
txt3.place(x=1100, y=200)
saveBtn = tk.Button(window, text="Save", command=SaveInDB ,width=20 )
saveBtn .place(x=900, y=300)
This code above does not work for me..Please help
You can check if the entry has any value and if not use showinfo to display a popup message. If you don't want a popup you can simply set the focus like entry.focus() or highlight the background with a different color. A minimal example of what you are trying to accomplish.
import tkinter as tk
from tkinter.messagebox import showinfo
def onclick():
if entry.get().strip():
print("Done")
else:
showinfo("Window", "Please enter data!")
#or either of the two below
#entry.configure(highlightbackground="red")
#entry.focus()
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
tk.Button(root, text='Save', command=onclick).pack()
root.mainloop()
Pop up version
Focus version
Background color version

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