how to get tkinter messagebox pop in front of toplevel in class - python

Is there a way to get the messagebox to appear in front of the toplevel?
code:
showwarning('warning','input four parameters!') shows the messagebox in front of mainwindow not toplevel window.
I checked the similar question root = Tk() texto = Toplevel(root) showinfo("title", "message") and the solution is ,showinfo("title", "message",parent=texto)
while I use class,there is no parent defination.
from tkinter import *
from tkinter.ttk import *
from tkinter.messagebox import *
import os
currentpath=os.path.dirname(__file__)
class AcurateQueryWindow(Toplevel):
def __init__(self,all_node_list:list):
super().__init__()
self.title("AcurateQuery")
self.width = 600
self.heigh = 500
self.screenwidth = self.winfo_screenwidth()
self.screenheight = self.winfo_screenheight()
self.geometry('%dx%d+%d+%d'%(self.width, self.heigh, (self.screenwidth-self.width)/2, (self.screenheight-self.heigh)/2))
self.resizable(0,0)
self.focus_set()
self.all_node_list = all_node_list
self.acurate_query_node_list=[]
self.setup_UI()
def setup_UI(self):
self.Style01 = Style()
self.Style01.configure("title.TLabel", font=("Helvetica", 25, "bold"), foreground="navy")
self.Style01.configure("pass.TLabel", font=("Helvetica", 15, "bold"), foreground="navy")
self.Style01.configure("TButton", font=("Helvetica", 12, "bold"))
self.Login_image = PhotoImage(file=currentpath+ os.sep + "img" + os.sep + "stu_detail_banner.png")
self.Label_image = Label(self, image=self.Login_image)
self.Label_image.pack()
# title
self.Label_title = Label(self, text="==AcurateQuery==", style="title.TLabel")
self.Label_title.place(x=280, y=15)
# pane
self.Pane_detail = PanedWindow(self, width=590, height=380)
self.Pane_detail.place(x=5, y=88)
#
self.Label_rlinemin = Label(self.Pane_detail,text = "rlinemin:",style = "pass.TLabel")
self.Label_rlinemin.place(x=160,y=70)
self.var_rlinemin = StringVar()
self.Entry_rlinemin = Entry(self.Pane_detail,textvariable = self.var_rlinemin , font=("Helvetica", 15, "bold"),width = 12)
self.Entry_rlinemin.place(x=280,y=68)
#
self.Label_rlinemax = Label(self.Pane_detail, text="rlinemax:",style = "pass.TLabel")
self.Label_rlinemax.place(x=160, y=120)
self.var_rlinemax = StringVar()
self.Entry_rlinemax = Entry(self.Pane_detail,textvariable=self.var_rlinemax, font=("Helvetica", 15, "bold"), width=12)
self.Entry_rlinemax.place(x=280, y=118)
#
self.Label_rpointmin = Label(self.Pane_detail, text="rpointmin:",style = "pass.TLabel")
self.Label_rpointmin.place(x=160, y=170)
self.var_rpointmin = StringVar()
self.Entry_rpointmin = Entry(self.Pane_detail,textvariable=self.var_rpointmin, font=("Helvetica", 15, "bold"), width=12)
self.Entry_rpointmin.place(x=280, y=168)
#
self.Label_rpointmax = Label(self.Pane_detail, text="rpointmax:",style = "pass.TLabel")
self.Label_rpointmax.place(x=160, y=220)
self.var_rpointmax = StringVar()
self.Entry_rpointmax = Entry(self.Pane_detail,textvariable=self.var_rpointmax, font=("Helvetica", 15, "bold"), width=12)
self.Entry_rpointmax.place(x=280, y=218)
#
self.Button_save = Button(self, text="query", style="TButton",command = self.query)
self.Button_save.place(x=300, y=452)
self.Button_exit = Button(self, text="close", style="TButton",command = self.close_window)
self.Button_exit.place(x=450, y=452)
def close_window(self):
self.destroy()
def query(self):
if len(self.Entry_rlinemin.get())==0 or len(self.Entry_rlinemax.get())==0 or len(self.Entry_rpointmin.get())==0 or len(self.Entry_rpointmax.get())==0:
showwarning('warning','input four parameters!')
pass
else:
rlinemin=int(str(self.Entry_rlinemin.get()).strip())
rlinemax=int(str(self.Entry_rlinemax.get()).strip())
rpointmin=int(str(self.Entry_rpointmin.get()).strip())
rpointmax=int(str(self.Entry_rpointmax.get()).strip())
if rlinemin>rlinemax or rpointmin>rpointmax:
showwarning('warning','max must bigger than min')
else:
self.acurate_query_node_list.append([rlinemin,rlinemax,rpointmin,rpointmax])
self.destroy()
return self.acurate_query_node_list
Is there a way to get the messagebox to appear in front of the toplevel while I use class?

Related

could not convert string to float: '' error in python(Tkinter)

I made a program that converts 1 currency to another(in this case only won to dollars). However, when I try to click on US radio button, it says "could not convert string to float: '' ". So, what's the problem here? I tried to run it without an additional window, and it worked perfectly fine, but when I open a converter window in a new window, it does not work. What is the problem and how do I make it so the converter would work fine when you open it in a new window?
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showerror
from tkinter import *
root = tk.Tk()
root.geometry('5000x5000')
def openconverter():
root = tk.Tk()
root.title('Change Converter')
root.geometry('400x210')
def won_to_dollar(f):
US = 0.00079
return f*US
frame = ttk.Frame(root)
options = {'padx': 5, 'pady': 5}
won = tk.StringVar()
won_entry = ttk.Entry(frame, textvariable=won)
won_entry.grid(column=1, row=0, **options)
def convert_button_clicked(won_to_dollar):
try:
f = float(won.get())
c = won_to_dollar(f)
result = f'{f} won = {c:.2f}'
result_label.config(text=result)
except ValueError as error:
showerror(title='Error', message=error)
result_label = ttk.Label(frame)
result_label.grid(row=1, columnspan=3, **options)
frame.grid(padx=10, pady=10)
r = IntVar()
Radiobutton(root, text="US", variable = r, value = 1, command = lambda : convert_button_clicked(won_to_dollar)).place(x = 220, y = 20)
myLabel = Label(root, text = r.get())
myLabel.grid
root.mainloop()
Converted = Button(root, text="converter",font = ("Helvetica", 15), width=50, height=50, compound="c", activeforeground = "green", command = lambda: openconverter())
Converted.place(x=10, y=185)
root.mainloop()
Try this and click convert and enter value and select US.
from tkinter import ttk
from tkinter.messagebox import showerror
from tkinter import *
root = Tk()
root.title('Change Converter')
root.geometry('400x810')
def openconverter():
def won_to_dollar(f):
US = 0.00079
return f*US
frame = Frame(root)
options = {'padx': 5, 'pady': 5}
won = StringVar()
won_entry = Entry(frame, textvariable=won)
won_entry.grid(column=1, row=0, **options)
def convert_button_clicked(won_to_dollar):
try:
f = won.get()
c = won_to_dollar(float(f))
result = f'{f} won = {c}'
result_label.config(text=result)
except ValueError as error:
showerror(title='Error', message=error)
result_label = Label(frame)
result_label.grid(row=1, columnspan=3, **options)
frame.grid(padx=10, pady=10)
r = IntVar()
Radiobutton(root, text="US", variable = r,
value = 1,
command = lambda : convert_button_clicked(won_to_dollar)).place(x = 220, y = 20)
myLabel = Label(root, text = r.get())
myLabel.grid
Converted = Button(root, text="converter",
font = ("Helvetica", 15), width=50, height=50, compound="c",
activeforeground = "green", command = lambda: openconverter())
Converted.place(x=10, y=5)
root.mainloop()

how to go into another windows in tktinker and destroy the previous window

code
'''here is code for login'''
from tkinter import*
from PIL import ImageTk
from home import product
from tkinter import messagebox
import mysql.connector
try:
mydb1=mysql.connector.connect(
host='localhost',
user='root',
passwd='',
database='gg'
)
mycursor=mydb1.cursor()
except mysql.connector.Error as error:
messagebox.showinfo("Information", "No Server Connection")
exit(0)
class Please_Login:
def __init__ (self,root):
self.root=root
self.root.title("Please Login")
self.root.geometry("640x426+100+50")
self.root.resizable(False, False)
# self.bg=ImageTk.PhotoImage(file='Desktop/sanju.jpg')
# self.bg_image=Label(self.root,image=self.bg).place(x=0,y=0,relwidth=1,relheight=1)
global usename1
global rollno1
#frame login
Frame_login = Frame(self.root, bg="white")
Frame_login.place(x=305,y=70, height=340, width=320)
#label for interface heading
title = Label(Frame_login, text="LOGIN SYSTEM !!", font=("bahnschrift", 15, "bold"),
fg="black", bg="white").place(x=10, y=20)
sam = Label(Frame_login, text="please login in here", font=("arial", 12, "bold"),
fg="black", bg="white").place(x=10, y=50)
self.namevar=StringVar()
self.pwvar=StringVar()
#label and entry for username
self.lbluser = Label(Frame_login, font=('Bahnschrift', 12, "bold"), text="USER NAME:"
, fg="black", bg="white").place(x=10, y=90)
self.txt_username = Entry(Frame_login, font=("Goudy old style", 15), bg="lavender",textvariable=self.namevar)
self.txt_username.place(x=130, y=90, width=170, height=25)
#label and entry for password
self.lbluser = Label(Frame_login, font=('Bahnschrift', 12, "bold"), text="PASSWORD:"
, fg="black", bg="white").place(x=10, y=130)
self.txt_userpw = Entry(Frame_login, font=("Goudy old style", 15), bg="LAVENDER",textvariable=self.pwvar,show="*")
self.txt_userpw.place(x=130, y=130, width=170, height=25)
#login button
self.login = Button(self.root, text="LOGIN", bg="white", fg="black",command=self.loginAdd ,font=("Bahnschrift", 15, "bold"))
self.login.place(x=330, y=250, width=250,height=30)
#sign up button
signup=Button(self.root,text="SIGN UP",bg="white",fg="black",
font=("Bahnschrift",15,"bold")).place(x=330, y=290, width=250, height=30)
#reset button
reset= Button(self.root, text="RESET", bg="white", fg="black",
font=("Bahnschrift", 15, "bold")).place(x=330, y=330, width=250, height=30)
# forget password button
forget = Button(Frame_login, text="Forget Password?", bg="white", fg="black", bd=0,
font=("Bahnschrift", 10, "bold")).place(x=10, y=310)
def loginAdd(self):
username1 = self.txt_username.get()
rollno1 = self.txt_userpw.get()
sql="SELECT * FROM login where username=%s"
value=(username1,)
mycursor.execute(sql, value)
myresult = mycursor.fetchall()
for i in myresult:
id = i[0]
pw = i[1]
if (username1 == "" or rollno1 == ""):
messagebox.showinfo("Information", "Fill all the fields")
elif (username1==id and rollno1==pw):
self.reg = Toplevel(self.root)
self.root.destroy()
product(self.reg)
else:
messagebox.showinfo("Information","enter correct password and username")
root=Tk()
Please_Login(root)
root.mainloop()
'''here is the code for home buttn'''
from tkinter import*
from PIL import ImageTk
import company
import manifest
class product:
def __init__(self, root):
self.root = root
self.root.title("WAREHOUSE MANAGEMENT SYSTEM")
self.root.geometry("1024x768+0+0")
self.root.resizable(False, False)
# self.bg = ImageTk.PhotoImage(file='Desktop/hello.jpg')
# self.bg_image = Label(self.root, image=self.bg).place(x=0, y=0, relwidth=1, relheight=1)
self.b1=Button (self.root,text="COMPANY",command=self.addcompany,font=('bahnschrift',20,'bold'))
self.b2 = Button(self.root,text="MAINFEST",command=self.addcompany,font=('bahnschrift',20,'bold'))
self.b3 = Button(self.root,text="WAREHOUSE",font=('bahnschrift',20,'bold'))
self.b4 = Button(self.root,text="UPDATE",font=('bahnschrift',20,'bold'))
self.b5 = Button(self.root,text="SHIPMENT",font=('bahnschrift',20,'bold'))
self.b6 = Button(self.root,text="QUIT",font=('bahnschrift',20,'bold'))
self.b1.place(x=30, y=50)
self.b2.place(x=30,y=150)
self.b3.place(x=30, y=250)
self.b4.place(x=30, y=350)
self.b5.place(x=30, y=450)
self.b6.place(x=30, y=550)
def addcompany(self):
self.reg = Toplevel(self.root)
company.product(self.reg)
def addmanifest(self):
self.reg = Toplevel(self.root)
manifest.product(self.reg)
From what I can tell of your question, what you want to do is something like:
I don't know classes so you can add them on your own.
def loginaccepted():
home = Toplevel()
root.withdraw()
Toplevel() creates a child of Tk() and root.withdraw() destroys the window. If you want the window back you can use root.deiconify()
Again, I dont understand classes, hopefully this answers your question!

displaying image on tkinter python 2.7 widget in my code

I am a beginner in Python, I want to add an image to the widget that I have made with the code below, the display size is 1024 * 600 px / full screen, I use LCD 7 inc. is someone helping me to do that?
import time
import serial
from Tkinter import *
serial_speed = 115200
serial_port = '/dev/ttyACM0'
ser = serial.Serial(serial_port, serial_speed, timeout=1)
class Application(Frame):
def measure(self):
ser.write("m")
data = ser.readline()
# If the answer is not empty, process & display data
if (data != ""):
processed_data = data.split(",")
self.tegangan_data.set("TEGANGAN: " + str(processed_data[0]))
self.tegangan.pack()
self.arus_data.set(" ARUS : " + str(processed_data[1]))
self.arus.pack()
self.daya_data.set(" DAYA : " + str(processed_data[2]))
self.daya.pack()
self.torsi_data.set(" TORSI : " + str(processed_data[3]))
self.torsi.pack()
self.panas_data.set(" PANAS MESIN : " + str(processed_data[4]))
self.panas.pack()
self.jarak_data.set(" JARAK TEMPUH : " + str(processed_data[5]))
self.jarak.pack()
# Wait 1 second between each measurement
self.after(500,self.measure)
# Create display elements
def createWidgets(self):
self.tegangan = Label(self, textvariable=self.tegangan_data, font=('Verdana', 20, 'bold'))
self.tegangan_data.set("Tegangan")
self.tegangan.pack()
self.arus = Label(self, textvariable=self.arus_data, font=('Verdana', 20, 'bold'))
self.arus_data.set("Arus")
self.arus.pack()
self.daya = Label(self, textvariable=self.daya_data, font=('Verdana', 20, 'bold'))
self.daya_data.set("Daya")
self.daya.pack()
self.torsi = Label(self, textvariable=self.torsi_data, font=('Verdana', 20, 'bold'))
self.torsi_data.set("Torsi")
self.torsi.pack()
self.panas = Label(self, textvariable=self.panas_data, font=('Verdana', 20, 'bold'))
self.panas_data.set("Panas mesin")
self.panas.pack()
self.jarak = Label(self, textvariable=self.jarak_data, font=('Verdana', 20, 'bold'))
self.jarak_data.set("Daya")
self.jarak.pack()
def __init__(self, master=None):
Frame.__init__(self, master)
self.tegangan_data = StringVar()
self.arus_data = StringVar()
self.daya_data = StringVar()
self.torsi_data = StringVar()
self.panas_data = StringVar()
self.jarak_data = StringVar()
self.createWidgets()
self.pack()
self.measure()
root = Tk()
app = Application(master=root)
app.mainloop()
look like this (in link), I want to add an image right below it (in full window)
https://i.stack.imgur.com/c4pVF.jpg

Making a new window with an input widget using tkinter

I can't seem to make my new window display the inputer code
it only displays a new empty window without the labels and the input widget
i want to make a simple GUI for a school project, but i dont want to type the name in the python shell, but in the interface
please help and tell me where im wrong, im still new to python
from collections import deque
first = deque([])
last = deque([])
nom = 0
import tkinter as tk
from tkinter import *
class Application(tk.Frame):
def __init__(self, master=None, nom=0, priono=1, prio=1):
super().__init__(master)
self.pack()
self.create_widgets()
self.nom= nom
self.priono= priono
self.prio=prio
def create_widgets(self):
self.add = tk.Button(self, bg ="black", fg="pink")
self.add["text"] = "-----Add to queue-----\n(click me)"
self.add["command"] = self.create_window
self.add.pack(side="top", pady = 10, padx = 20)
self.add["font"] = "Times 16 bold"
self.remov = tk.Button(self, bg ="black", fg="pink")
self.remov["text"]= "---Remove in queue---\n(click me)"
self.remov["command"] = self.remov_
self.remov.pack(side="top", pady = 10, padx = 20)
self.remov["font"] = "Times 16 bold"
self.quit = tk.Button(self, text="QUIT", fg="white", bg = "red",
command=root.destroy)
self.quit.pack(side="bottom")
def create_window(self):
def inputer(self):
self.L1 = tk.Label(self, text = "Name")
self.L1.pack( side = LEFT)
self.E1 = tk.Entry(self, bd =5)
self.E1.pack(side = RIGHT)
win2 = Toplevel(self)
win2.button = Button(self, text='Ready?\nClick Here', command=inputer)
def say_hi(self):
print("hi there, everyone!")
def add_1(self):
name=input("What is your name? ")
first.append(name)
print("Good Day!",first[self.nom])
print("Your priority number is:","%03d" % (self.priono))
self.priono+=1
self.nom+= 1
def remov_(self):
if (len(first)) >= 1:
first.popleft()
else:
print("No one left in queue")
root = tk.Tk()
root.config(background="black")
app = Application(master=root)
app.master.title("ID QUEUEING SYSTEM beta")
app.master.minsize(540, 360)
app.master.maxsize(600, 500)
app.mainloop()
You must use your toplevel to indicate where the widgets must appear; you must also pack (place or grid) the widgets belonging to your toplevel window.
The code from inputer needed to be placed outside of the inner function; you can now write the code to have this inputer do what you need it to do:
I removed the star import and added the prefix tk. to all tkinter method calls.
import tkinter as tk
from collections import deque
class Application(tk.Frame):
def __init__(self, master=None, nom=0, priono=1, prio=1):
super().__init__(master)
self.pack()
self.create_widgets()
self.nom = nom
self.priono= priono
self.prio=prio
def create_widgets(self):
self.add = tk.Button(self, bg ="black", fg="pink")
self.add["text"] = "-----Add to queue-----\n(click me)"
self.add["command"] = self.create_window
self.add.pack(side="top", pady = 10, padx = 20)
self.add["font"] = "Times 16 bold"
self.remov = tk.Button(self, bg ="black", fg="pink")
self.remov["text"]= "---Remove in queue---\n(click me)"
self.remov["command"] = self.remov_
self.remov.pack(side="top", pady = 10, padx = 20)
self.remov["font"] = "Times 16 bold"
self.quit = tk.Button(self, text="QUIT", fg="white", bg = "red",
command=root.destroy)
self.quit.pack(side="bottom")
def create_window(self):
def inputer():
print('inputer ', end=': ')
print(self.E1.get())
win2 = tk.Toplevel(self)
win2_button = tk.Button(win2, text='Ready?\nClick Here', command=inputer)
win2_button.pack()
self.L1 = tk.Label(win2, text = "Name")
self.L1.pack( side=tk.LEFT)
self.E1 = tk.Entry(win2, bd =5)
self.E1.pack(side=tk.RIGHT)
def say_hi(self):
print("hi there, everyone!")
def add_1(self):
name=input("What is your name? ")
first.append(name)
print("Good Day!",first[self.nom])
print("Your priority number is:","%03d" % (self.priono))
self.priono+=1
self.nom+= 1
def remov_(self):
if (len(first)) >= 1:
first.popleft()
else:
print("No one left in queue")
root = tk.Tk()
root.config(background="black")
app = Application(master=root)
app.master.title("ID QUEUEING SYSTEM beta")
app.master.minsize(540, 360)
app.master.maxsize(600, 500)
app.mainloop()

How can i erase contents in a Label?

Sorry for the mess
so I am making a seating chart, and I cant seem to get it working properly... again. I am trying to make the label reset every time i press the run button, any ideas?
#commands: add name , Run
#imports
import random
from time import sleep
from tkinter import *
#Console and background Handlers
Tables = 6
Names = []
def AddNames():
NewNames = e.get("1.0", 'end -1c')
if NewNames in Names:
print("Name Already exists")
elif NewNames == "":
print("Empty")
else:
Names.append(NewNames)
print(Names)
e.delete(1.0, END)
def Random():
RandomNum = random.randrange(Tables)
if RandomNum == 0:
RandomNum = random.randrange(Tables)
return RandomNum
def run():
X = 0
for i in Names:
#print(Names[X])
print("Table: " + str(Random()))
X += 1
#text = Label(popup, text = "")
text = Label(popup, text= Names[X] + "\n" + "Table: " + str(Random()))
text.pack()
#GUI Handler
root = Tk()
root.geometry("1024x768")
e = Text(root, bd = 10, font=("Comic Sans MS", 50) ,width = 15, height = 2)
e.pack()
popup = Toplevel()
popup.title("Seating Chart")
AddNameButton = Button(root, text = ("Add Name"), width = 15, height = 5, command = AddNames)
AddNameButton.pack()
RunButton = Button(root, text = ("Run"), width = 15, height = 5, command = run)
RunButton.pack()
root.mainloop()
I am trying to reset text every time the user presses the run button
import tkinter
from tkinter import ttk
import random
class MyApp:
def __init__(self):
self.root = tkinter.Tk()
self.seatwindow = None
self.root.title('Add Names')
self.currentname = tkinter.StringVar()
self._maxtables = tkinter.StringVar()
self.addednames = []
self.commandframe = ttk.Labelframe(self.root, text='Commands')
self.nameentry = ttk.Entry(self.root, textvariable=self.currentname)
self.addbutton = ttk.Button(self.root, text='Add Name', command=self.addname)
self.maxtablabel = ttk.Label(self.root, text='Tables: ')
self.maxtabentry = ttk.Entry(self.root, textvariable=self._maxtables)
self.genbutton = ttk.Button(self.commandframe, text='Run', command=self.generate)
self.resetbutton = ttk.Button(self.commandframe, text='Reset', command=self.reset)
self._maxtables.set('6')
self.nameentry.grid(row=0, column=0)
self.addbutton.grid(row=0, column=1, sticky='nsew')
self.maxtabentry.grid(row=1, column=1, sticky='nsw')
self.maxtablabel.grid(row=1, column=0, sticky='nse')
self.genbutton.grid(row=0, column=0, sticky='nsew')
self.resetbutton.grid(row=0, column=1, sticky='nsew')
self.commandframe.grid(row=2, column=0, columnspan=2, sticky='nsew')
self.nameentry.bind('<Return>', self.addname)
self.root.bind('<Control-Return>', self.generate)
def addname(self, event=None):
name = self.currentname.get()
if not(name == '' or name in self.addednames):
self.addednames.append(name)
self.currentname.set('')
else:
self.currentname.set('Name already added!')
def generate(self, event=None):
if not self.seatwindow == None:
self.seatwindow.destroy()
self.currentname.set('')
self.seatwindow = tkinter.Toplevel()
random.shuffle(self.addednames)
tables = []
for i in range(self.maxtables):
tableframe = ttk.Labelframe(self.seatwindow, text='Table ' + str(i + 1) + ':')
tableframe.grid(column=i, row=0, sticky='nsew')
tables.append(tableframe)
for index, name in enumerate(self.addednames):
namelabel = ttk.Label(tables[index%self.maxtables], text=name)
namelabel.grid(column=0, row=index//self.maxtables + 1)
def reset(self):
self.currentname.set('')
self.maxtables = 6
self.addednames = []
def run(self):
self.root.mainloop()
#property
def maxtables(self):
return int(self._maxtables.get())
MyApp().run()

Categories

Resources