Tkinter Mysql windows - python

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

Related

Why the image didn't come out in python?

I try to add image in tkinter but it didn't show up but when I added label of text,the text show but the image didn't.Thank you
from tkinter import *
class window1:
def __init__(self, parent, word, geometry):
# image
bank_img = PhotoImage(file='C:\\Users\\user\\PycharmProjects\\pythonProject3\\bank-988164_640.png')
self.parent = parent
self.word = word
self.geometry = geometry
parent.geometry(geometry)
parent.title(self.word)
# Label
label = Label(parent, text="Welcome to the bank", height=3).pack()
bank_logo = Label(parent,image=bank_img).pack()
root = Tk()
app = window1(root, 'beginner bank system', '300x300')
Add root.mainloop() at the end.
root = Tk()
app = window1(root, 'beginner bank system', '300x300')
root.mainloop()

"NameError[Command Name] is not defined" When Using Buttons in Tkinter

I'm trying to set up a list of checkbuttons from top to bottom in the GUI and add up the associated "onvalues" for each of the checkbuttons that are on.
My problem now is that for some reason my 'command' attribute in my 'calcbutton' is giving me a "Name 'calc_cost' is not defined" error.
I've added a bunch of imports that you see at the top of the code hoping that would solve the problem, to not much avail.
import tkinter as tk
from tkinter import *
from tkinter import Button
servicelist = ("Oil change","Lube job","Radiator flush","Transmission flush","Inspection","Muffler replacement","Tire rotation")
servicecost = (30,20,40,100,35,200,20)
a = 0
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def calc_cost(self):
print(a)
def init_window(self):
self.master.title("GUI")
self.pack(fill=BOTH, expand=1)
for i in range(len(servicelist)):
serviceButton = Checkbutton(self, text=servicelist[i], onvalue = servicecost[i], var = a)
serviceButton.place(x=0, rely = i*.1)
calcButton = tk.Button(self, text = "Calculate Cost", fg = "black", bg = "green", command = calc_cost)
calcButton.pack(side = "bottom")
root = Tk()
#size of the window
root.geometry("400x300")
app = Window(root)
root.mainloop()
The checkbuttons pop up and the GUI works for the most part besides the displaying of the 'calcbutton' as well as getting the "NameError: name 'calc_cost' is not defined"
Change command = calc_cost to command = self.calc_cost
self represents the instance of the class. By using the self keyword we can access the attributes and methods of the class in python.
It will give you this output

Tkinter images crashing

So I made a script in python with Tkinter and the thing is that the first Tkinter window pops up without problems but when the code goes to the second window it says :
_tkinter.TclError: image "pyimage1" doesn't exist
and I didn't find anything that helped me, could someone help me please ?
Here is the code :
from Tkinter import *
from PIL import ImageTk, Image
def choose():
global name, chosen
name = name1.get()
chosen = chosen1.get()
print name
print chosen
root0.quit()
root0 = Tk()
name1 = Entry(root0)
name1.pack()
chosen1 = Entry(root0)
chosen1.pack()
Button(root0, text="ENTER", command=choose).pack()
root0.mainloop()
root = Tk()
img = ImageTk.PhotoImage(Image.open('person1.png'))
panel1 = Label(root, image = img)
panel1.pack(side="left")
img2 = ImageTk.PhotoImage(Image.open('person2.png'))
panel2 = Label(root, image = img2)
panel2.pack(side="right")
root.mainloop()
by the way, the python version is 2.7
This is a side effect of using 2 roots (Tk() instances). The images default to associate with the first root window. The quick fix is to provide the image with the correct root:
img2 = ImageTk.PhotoImage(Image.open('person2.png'), master=root)
The proper fix is to never use more than one Tk(). Put all your code into Frame instances, and then destroy one and load the other when the time is right:
import Tkinter as tk
def choose():
global name, chosen
name = name1.get()
chosen = chosen1.get()
print name
print chosen
frame0.destroy() # kill this frame
frame1.pack() # open new frame
root = tk.Tk()
frame0 = tk.Frame(root)
name1 = tk.Entry(frame0)
name1.pack()
chosen1 = tk.Entry(frame0)
chosen1.pack()
tk.Button(frame0, text="ENTER", command=choose).pack()
frame1 = tk.Frame(root)
img = ImageTk.PhotoImage(Image.open('person1.png'))
panel1 = tk.Label(frame1, image = img)
panel1.pack(side="left")
img2 = ImageTk.PhotoImage(Image.open('person2.png'))
panel2 = tk.Label(frame1, image = img2)
panel2.pack(side="right")
#start the program
frame0.pack() # load frame0
root.mainloop()
Note I also moved you away from the evil wildcard imports (from module import *).

Tkinter - Open one window and close another

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()

python 2.7 Tk change label to carry file name from opened file

I have this code in python 2.7 using tkinter that creates a Button on a Frame to open a file. There's a Label under it. I'm trying to make it so once the file is opened, the label prints the path, "file1.name" or whatever, on the Label, and if you open a new file it will change that Label again.
Also, I'm betting there's a better way to move data between the functions than I'm using here with global, but that's not worrying me right now.
I have to move the data from the opened files between functions so that I can mix the data and save to a new file. The code is:
from Tkinter import *
import Tkinter
import tkFileDialog
import tkMessageBox
root = Tkinter.Tk()
global rfile1
global rfile2
rfile1 = ""
rfile2 = ""
class Application(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.grid()
self.createWidgets1()
self.createLabels1()
self.createWidgets2()
self.createLabels2()
def createWidgets1(self):
self.oButton = Button(self, text = "open1", command = self.openfile1)
self.oButton.grid()
def createLabels1(self):
self.oLabel = Label(self, text = "whoops")
self.oLabel.grid()
def createWidgets2(self):
self.oButton = Button(self, text = "open2", command= self.openfile2)
self.oButton.grid()
def createLabels2(self):
self.oLabel2 = Label(self, text = "whoops2")
self.oLabel2.grid()
def openfile1(self):
file1 = tkFileDialog.askopenfile(title = "choose a file, *****", parent=root, mode = 'rb')
rfile1 = file1.read()
tkMessageBox.showinfo("oy", rfile1, parent=root)
def openfile2(self):
file2 = tkFileDialog.askopenfile(parent=root, mode='rb')
rfile2 = file2.read()
tkMessageBox.showinfo("hola", rfile2, parent=root)
app = Application()
app.master.title("whiggy whompus")
app.mainloop()
If I understand correctly, you want something like (untested):
def openfile1(self):
file1 = tkFileDialog.askopenfile(title = "choose a file, *****", parent=root, mode = 'rb')
self.oLabel.configure(text=file1.name)
rfile1 = file1.read()
tkMessageBox.showinfo("oy", rfile1, parent=root)
#mgilson has solved your first question. Your second question, about how to pass parameters between functions without using globals :
you might want to look at storing the variables as attributes on your application class :
The syntax self. is an attribute on the current instance (an instance being a particular example of a class - just like your car is a specific example of a class "car").
You can use instance attributes in this example as if they are globals.
from Tkinter import *
import Tkinter
import tkFileDialog
import tkMessageBox
root = Tkinter.Tk()
class Application(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.grid()
self.createWidgets1()
self.createLabels1()
self.createWidgets2()
self.createLabels2()
self.rfile1 = ""
self.rfile2 = ""
def createWidgets1(self):
self.oButton = Button(self, text = "open1", command = self.openfile1)
self.oButton.grid()
def createLabels1(self):
self.oLabel = Label(self, text = "whoops")
self.oLabel.grid()
def createWidgets2(self):
self.oButton = Button(self, text = "open2", command= self.openfile2)
self.oButton.grid()
def createLabels2(self):
self.oLabel2 = Label(self, text = "whoops2")
self.oLabel2.grid()
def openfile1(self):
file1 = tkFileDialog.askopenfile(title = "choose a file, *****", parent=root, mode = 'rb')
self.rfile1 = file1.read()
tkMessageBox.showinfo("oy", self.rfile1, parent=root)
def openfile2(self):
file2 = tkFileDialog.askopenfile(parent=root, mode='rb')
self.rfile2 = file2.read()
tkMessageBox.showinfo("hola", self.rfile2, parent=root)
app = Application()
app.master.title("whiggy whompus")
app.mainloop()

Categories

Resources