I want to have a login screen and when the login is successful, the screen is closed and a new screen is created. The problem is , when I do just like the following code , both screens opens at the same time. If you have any suggestions to improve the code , please do! :)
from Tkinter import *
import mysql.connector
import tkMessageBox
class Tela_login(Frame):
root = Tk()
root.geometry("1024x768")
root.resizable(width=FALSE, height=FALSE)
background_image = PhotoImage(file="fundo.gif")
def __init__(self,master):
Frame.__init__(self,master)
self.grid()
fundo = Label(image=self.background_image)
fundo.place(x=0,y=0,relwidth=1,relheight=1)
self.create_screen()
def create_screen(self):
self.label1 = Label(text="Login",font = ("Arial",60))
self.label2 = Label(text="Senha",font = ("Arial",60))
self.login = Entry(font = ("Arial",60),width = 10)
self.senha = Entry(show="*",font = ("Arial",60), width= 10)
self.entrar = Button(text="Entrar",command=lambda : self.efetua_login(),font = ("Arial",60),width=10)
self.label1.grid(padx=258,pady=(70,0))
self.login.grid(padx=258)
self.label2.grid(padx=258,pady=(50,0))
self.senha.grid(padx=258)
self.entrar.grid(padx=258,pady=(50,0))
def efetua_login(self):
login = self.login.get()
senha = self.senha.get()
cnx = mysql.connector.connect(user='root', password='123qwe', host='192.168.56.1', database='teste')
cursor = cnx
cursor = cnx.cursor()
query = ("SELECT nome, senha FROM funcionario WHERE nome = %s AND senha = %s")
cursor.execute(query, (login,senha))
row = cursor.fetchone()
if row is None:
tkMessageBox.showinfo("Erro","Usuario ou Senha Incorretos")
else:
app2 = Tela_principal()
self.root.destroy()
Tela_principal.root.mainloop()
class Tela_principal(Frame):
root = Tk()
root.geometry = ("1024x768")
root.resizable(width=FALSE, height=FALSE)
def inicia(self, master):
background_image = PhotoImage(file="fundo.gif")
app2 = Tela_principal(self.root)
Frame.__init__(self, master)
self.grid()
self.create_widgets()
app = Tela_login(Tela_login.root)
Tela_login.root.mainloop()
You probably don't want to have two Tk() instances running. For the login screen there's two routes you could go. You could withdraw the root window and make the login screen a Toplevel withdrawing the root window upon the Toplevel's initialization window and once the login is successful destroy the toplevel and raise the root window. Or, even easier you could put your login screen in a separate frame, hide the main frame using pack_forget or grid_forget depending on your layout and then login / destroy or hide the frame and recall pack or grid to show the main app frame again.
Slayer , I did like you said and it worked like a charm!
Here is the example code:
from tkinter import *
class Tela_login(Frame):
def __init__(self,master):
Frame.__init__(self, master)
self.grid()
self.button1 = Button(text = "Open",command = lambda: self.open_login())
self.button1.grid()
def open_login(self):
root2 = Toplevel()
app2 = Tela_principal(root2)
class Tela_principal(Frame):
def __init__(self,master):
Frame.__init__(self, master)
self.grid
root = Tk()
root.geometry("800x600")
app = Tela_login(root)
root.mainloop()
Related
when i run python file kill_app its run first 2nd python file(Hb_test.py) then run 1st python on tkinter.i am using vs code and python version is 3.10
see the code below
from tkinter import*
from Lab.Hb_Test import Hba
class kill_App:
def __init__(self,root):
self.root = root
self.root.geometry("1350x700+0+0")
self.root.title("Billing Software")
bg_color = "#074463"
title = Label(self.root,text = "PATHOLAB",bd=12,relief=GROOVE,bg=bg_color,fg="white",
font = ("ALGERIAN",40),pady=2).pack(fill=X)
if __name__=="__main__":
root =Tk()
obj = kill_App(root)
root.mainloop()
****
this is my second
**
**from tkinter import*
from tkinter import ttk
class Hba:
def __init__(self,root):
self.root = root
self.root.geometry("300x70+200+200")
self.root.title("JIBAN PRABHA PATHOLAB")
bg_color = "#074463"
Hb = LabelFrame(self.root,text="BLOOD TEST",font=("ALGERIAN",15,"bold")
,fg="gold",bg=bg_color)
Hb.place(x=0,y=0)
self.hb_neu_lbl = Label(Hb,text="Hb%(sahils) Test",bg=bg_color,fg="white",font=("Bell MT",15,"bold")).grid(row=1,column=1,padx=5,pady=5)
self.hb_neu=Entry(Hb,width=10,font="BellMT 15",bd=5,relief=SUNKEN).grid(row=1,column=2,padx=5,pady=5)
root = Tk()
obj = Hba(root)
root.mainloop()**
**
When Hb_Test is imported, its code will be executed, so the last three lines in the module will create a window:
Hb_Test.py
...
# below lines will create a window
root = Tk()
obj = Hba(root)
root.mainloop()
Note that it is not recommended to create more than one instance of Tk() and execute .mainloop() more than once.
For window other than the main/root window, use Toplevel instead of Tk. For your case, I would suggest that Hba inherits from Toplevel:
import tkinter as tk
class Hba(tk.Toplevel):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
self.geometry("300x70+200+200")
self.title("JIBAN PRABHA PATHOLAB")
bg_color = "#074463"
Hb = tk.LabelFrame(self, text="BLOOD TEST", font=("ALGERIAN",15,"bold"), fg="gold", bg=bg_color)
Hb.place(x=0, y=0)
self.hb_neu_lbl = tk.Label(Hb, text="Hb%(sahils) Test", bg=bg_color, fg="white", font=("Bell MT",15,"bold"))
self.hb_neu_lbl.grid(row=1,column=1,padx=5,pady=5)
self.hb_neu = tk.Entry(Hb, width=10, font="BellMT 15", bd=5, relief=tk.SUNKEN)
self.hb_neu.grid(row=1,column=2,padx=5,pady=5)
Note that I have changed from tkinter import * to import tkinter as tk because wildcard import is not recommended as well.
Also don't write code like below:
self.hb_neu_lbl = Label(Hb,text="Hb%(sahils) Test",bg=bg_color,fg="white",font=("Bell MT",15,"bold")).grid(row=1,column=1,padx=5,pady=5)
because self.hb_neu_lbl will be None (result of .grid(...)). Code like below instead:
self.hb_neu_lbl = Label(Hb, text="Hb%(sahils) Test", bg=bg_color, fg="white", font=("Bell MT",15,"bold"))
self.hb_neu_lbl.grid(row=1,column=1,padx=5,pady=5)
import tkinter as tk
from tkinter import messagebox
import xlrd as rd
class Example():
def __init__(self,master):
self.frameExample =tk.Frame(master,width =600,height = 200)
self.frameExample.pack()
self.loadButton = tk.Button(self.frameExample,text = "Load",command =self.loadFile)
self.loadButton.pack()
def loadFile(self):
sheetWindow = tk.Toplevel()
sheetFrame = tk.Frame(sheetWindow, width = 600,height = 400,bg = "alice blue")
sheetFrame.pack()
try:
print("entered")
self.workbook = rd.open_workbook("tiger.jpg")
except:
print("entered 1")
messagebox.showinfo(title = "Load error",message = "Error")
self.master.destroy()
root = tk.Tk()
Example(root)
root.mainloop()
I have tried self.masterdestroy(), not sure how to kill main window
Just add self.master = master to your __init__ method and then your code should work.
I was able to connect mysql and python
enter image description here
I've create 2 labels, and I want to import the value from the Database(MySQL) to the label(tkinter) instead of 'text1' and 'text2'.
enter image description here
What is the function that i have to use?
or
How can i solve that?
from tkinter import *
from PIL import Image, ImageTk
import pymysql
conn = pymysql.connect(host = "localhost",
user = "root",
passwd = "asdf",
db = "testdb", charset = 'utf8')
curs = conn.cursor(pymysql.cursors.DictCursor)
sql = "select * from test where id=%s and text1=%s and text2=%s"
curs.execute(sql,('A0002','asdfasdfasdf', 'asdfasdfvvwervfvasff'))
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid(row=0)
self.columnconfigure(0,weight=1)
self.rowconfigure(0,weight=1)
self.original = Image.open('Chrysanthemum.jpg')
resized = self.original.resize((400, 300),Image.ANTIALIAS)
self.image = ImageTk.PhotoImage(resized)
self.display = Label(self, image = self.image)
self.display.grid(column=0,row=0)
root = Tk()
root.title("image test")
root.geometry("1000x800+100+100")
root.resizable(0,0)
root.configure(background = 'white')
app = App(root)
rows = curs.fetchall()
label1 = Label(root,text = "text1")
label1.config(wraplength =500)
label1.config(width=80,height=20)
label1.grid(column=1,row=0)
label2 = Label(root,text ="text2")
label2.config(wraplength=910)
label2.config(width=138,height=30)
label2.grid(columnspan=2,row=1)
app.mainloop()
To set the text of a label in Tkinter you can use StringVar and set it's value accordingly. Please see if the below code helps:
labelText1 = Stringvar()
label1 = Label(self, textvariable=labelText1)
The variable can be assigned using set function whenever there is update in the database:
labelText1.set(labelTextValue)
It would be great if you can give some more explanation on your problem.
Once you load the value from the sql db, you can store it in a variable and then do an update on the text.To update the value of a label simply use
label1.config(text='New Value')
I'll try to help you out if this doesn't make any sense
More reading
Changing the text on a label
http://effbot.org/tkinterbook/label.htm
I am trying to create a status/progress bar that shows how many web pages are left to scrape. I am getting lost on how to pass the # of pages between the modules. I think I am making a mistake by calling the tkinter window class. Any help on how to call this module and pass the pg/pages variables would be greatly appreciated.
Module getting page count:
from ProgressBar import StatusWindow
pages = 25
class crawler:
def get_pagecount():
for eachPage in range(1,pages):
pg = eachPage
Complete = '{:.0%}'.format(pg/pages)
print(Complete)
StatusWindow(pages,pg) """<== How do I call the progress bar and pass these variables?"""
if __name__=='__main__':
crawler.get_pagecount()
ProgressBar:
from tkinter import *
from tkinter import ttk
backRGB = '#e5e5e5'
root = Tk()
root.configure(bg=backRGB)
root.configure()
class StatusWindow(Frame,ToDo,Done): """<==Probably not where I should be calling and passing variables?"""
def __init__(self,master = None):
Frame.__init__(self,master)
self.master = master
self.init_window()
self.grid()
self.tk_setPalette(background='#e5e5e5', foreground = '#001030',activeBackground='#001030',activeForeground='white')
ToDo = 10
Done = 5
self.Progress_Bar(ToDo,Done)
def Progress_Bar(self,ToDo,Done):
progressbar = ttk.Progressbar(root, orient = HORIZONTAL, length = 300)
progressbar.grid(row=9, column = 0)
progressbar.config(mode = 'determinate', maximum = ToDo, value = Done)
def init_window(self):
self.master.title("Program Status")
self.pack(fill=BOTH, expand=1)
menu = Menu(self.master)
self.master.config(menu=menu)
text = Text(self.master)
app = StatusWindow(root)
root.mainloop()
I want my GUI to have a 'new window' option that will be just the same as the first one.
The problem is that it also has an exit(quit) button that won't work as it should - whenever I open the new window and then press the button, in the first click nothing happens and in the second one it closes both windows (if 3 windows are open so it'll close everything in the third click and so on).
This the relevant code:
from Tkinter import *
from ttk import *
class Application(Tk):
def __init__(self):
self.root = Tk()
self.root.geometry("250x150")
self.app = Frame(self.root)
self.app.grid()
self.create_menu()
self.create_widgets()
self.root.mainloop()
def create_menu(self):
menu = Menu(self.root)
self.root.config(menu=menu)
sub_menu = Menu(menu)
menu.add_cascade(label="File", menu=sub_menu)
sub_menu.add_command(label="New", command=self.__init__)
sub_menu.add_command(label="Run", command=self.enter)
sub_menu.add_separator()
sub_menu.add_command(label="Exit", command=self.app.quit)
I also tried to change:
sub_menu.add_command(label="New", command=self.__init__)
to:
sub_menu.add_command(label="New", command=self.new window)
Where:
def new_window(self):
class App(Application):
Application.__init__(self)
Both do the same thing.
How can I fix it?
In a Tkinter-Application there may only be one Tk-object. If the object is destroyed or destroyed by the garbage collector, Tkinter will be disabled. Use Toplevel for other other windows instead.
Try this instead:
from Tkinter import *
from ttk import *
class Application(object):
def __init__(self, master):
self.root = master
self.root.geometry("250x150")
self.app = Frame(self.root)
self.app.grid()
self.create_menu()
self.create_widgets()
def create_menu(self):
menu = Menu(self.root)
self.root.config(menu=menu)
sub_menu = Menu(menu)
menu.add_cascade(label="File", menu=sub_menu)
sub_menu.add_command(label="New", command=self.new)
sub_menu.add_command(label="Run", command=self.enter)
sub_menu.add_separator()
sub_menu.add_command(label="Exit", command=self.quit)
def new(self):
window = Toplevel(tk)
return Application(window)
def quit(self):
tk.destroy()
tk = Tk()
Application(tk)
tk.mainloop()