从MySQL获取数据库以输出标签Tkinter Python

2024-04-19 18:38:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望将我的SQL查询(来自MySQL数据库)的结果放在我创建的Tkinter的一个特定标签中(该标签称为cruncher_resu2)。但当我运行代码时,我所拥有的只是输入的内容。 My GUi with wrong output

import tkinter as tk;
import tkinter.ttk as tki;
from PIL import Image, ImageTk;
import mysql.connector; 
import config;


#Création de la fenêtre
fenetre = tk.Tk()
#Taille de la fenêtre
fenetre.geometry('1000x620')

def recherche(): 
   boxderecherche = srchbx_RS1.get()
   stringtodisplay = "vos resultats " + boxderecherche
   Cadre_resu2=tk.Label(o1)
   Cadre_resu2["text"]=stringtodisplay
   Cadre_resu2.place(relx=0.1,rely=0.5,relwidth=0.5,relheight=0.05)
   
def Cadre_resu2():
    # Connect to the database
    connection = mysql.connector.connect(host = '127.0.0.1',
                             user = config.user,
                             password = config.password,
                             db = 'bdd_cmatto')
    try:
        with connection.cursor() as cursor:
            # Assemble la requete SQL qui permet de crée et affecter la variable @name, 
            # celle-ci continet des '%' utilisée pour le LIKE
            sql = "SET @recherche='%" + recherche + "%';";
            #~ print(sql) # affiche pour debug
            cursor.execute(sql) # execute le STE @name...
            cursor.execute("SET @N=0;") # execute le STE @name...
            # Execute la recherche elle-même qui utilise @name
            cursor.execute("SELECT @N:=@N+1, nconst, primaryName FROM name_basics WHERE primaryName like @name;")
            # On récupère tout les résultats
            results = cursor.fetchall()
            cursor.close()
            #print(results)
            # Boucle pour afficher tout les resultats
            for result in results:
            #~ print(result)
                print("{:4d} : {:10s} : {}".format(result[0], result[1], result[2]))

    except:
        print("Quelque chose a mal tourné...")
 
    
    finally:
        connection.close()
        
#Paramètres graphiques de la fenêtre
style=tki.Style(fenetre)
style.theme_create( "MyStyle", parent="alt", settings={
        "TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0] } },
        "TNotebook.Tab": {"configure": {"padding": [50, 25],"font" : ('URW Gothic L', '11', 'bold')},}})
style.theme_use("MyStyle")
style.configure("Mine.TButton", background="white")

# Création du système d'onglets
onglets = tki.Notebook(fenetre,width='100', height="75")   
onglets.place(relx=0,rely=0,relwidth=1,relheight=1)

o1 = tki.Frame(onglets)       # Ajout de l'onglet 1
#o1.grid()
onglets.add(o1, text='Recherche')      # Nom de l'onglet 1

contents = {'Acteur', 'Réalisateur','Année de sortie','Film','Genre'} #A mettre dans la barre d'erreur 

search_text_var = tk.StringVar()
options_var = tk.StringVar()

options_var.set("Choisissez votre catégorie")
dropdown = tk.OptionMenu(o1, options_var, *contents) #fenêtre déroulante 
dropdown.pack()

search_text1 = tk.StringVar()
srchbx_RS1=tk.Entry(o1, width=110) # Entrée dans la barre de recherche
srchbx_RS1.place(relx=0.1,rely=0.1,relwidth=0.8,relheight=0.05) #emplacement
srchbx_RS1.bind("<Return>", recherche) #Action du bouton

#Creation Bouton "rechercher"
button=tki.Button(o1,text="rechercher", command= recherche)
button.place(relx=0.5,rely=0.2,relwidth=0.1,relheight=0.05)

#Position des cadres Resultat et Synthèse
Resultatrchr= tk.StringVar()
Cadre_resultat = tk.Label( o1, text="cadre de résultat", bg="white", textvariable=Resultatrchr).place(relx=0.1,rely=0.5,relwidth=0.5,relheight=0.05)
Cadre_Synthèse = tk.Label( o1, text="cadre synthèse", bg="white").place(relx=0.7,rely=0.5,relwidth=0.2,relheight=0.05)

o2= tki.Frame(onglets)       # Ajout de l'onglet 3
#o3.grid()
onglets.add(o2, text='Recommandations') # Nom de l'onglet 3

search_text2 = tk.StringVar()
srchbx_RS2=tk.Entry(o2,width=110) # Ajout barre de recherche
srchbx_RS2.pack()

#bouton rechercher
button=tk.Button(o2,text="rechercher")
button.pack()


Cadre_resultat2 = tk.Label( o2, text="cadre de résultat", bg="white").place(relx=0.25,rely=0.25,relwidth=0.5,relheight=0.25)


fenetre.mainloop()

我认为问题出在函数def recherche或def branker_resu2()中。 我是一个初学者,请友善一点 谢谢大家!


Tags: textplacedecursorlatko1rely
1条回答
网友
1楼 · 发布于 2024-04-19 18:38:27

多亏了你们,我才发现问题所在。我不知道如何使用函数

def fiche_acteur():
with connection.cursor() as cursor:
    xxx=s2.get()
    sql = "SET @name='%" + xxx + "%';";
    cursor.execute(sql)
    cursor.execute("""SELECT primaryName, birthYear, deathYear FROM name_basics 
                       WHERE primaryName like @name;""")
    result = cursor.fetchone()
    deathYear = result[2]
    if deathYear is None or deathYear =='':
        deathYear = '~~'
    cursor.execute("""SELECT primaryTitle,averageRating FROM title_principals
                       JOIN title_basics ON title_principals.tconst = title_basics.tconst
                       JOIN name_basics ON title_principals.nconst = name_basics.nconst
                       JOIN title_ratings on title_principals.tconst = title_ratings.tconst
                       WHERE primaryName like @name AND numVotes>1000
                       ORDER BY averageRating DESC
                       LIMIT 3;""")
    films = cursor.fetchall()
    liste_complete=[result,films]
    df_lc=pd.DataFrame(liste_complete)
    df_lc1=df_lc.rename(columns={0:'',1:'',2:''})
resultLabel2.config(text=df_lc1.to_string(index=False))


#Fenêtre principale
root = tk.Tk() 
root.geometry("1800x900") 
root.title("MoviePro")

root.configure(background='black')

#Style custom des onglets
style=tki.Style()
style.configure("fond.TFrame",background="black", foreground="white", borderwidth=1, font=("Ubuntu", 16, 'bold'))
style.configure("TNotebook", background="black", foreground="white",borderwidth=2, padding=[100,20] ,tabmargins= [2, 5, 2, 0], font=("Ubuntu", 18, 'bold'))
style.configure("TNotebook.Tab", background="black", foreground="white",borderwidth=2, padding= [100, 20], font=("Ubuntu", 18, 'bold'))

#Image logo
load= Image.open("CineLogo1.png")
resized= load.resize((400,250),Image.ANTIALIAS)
render = ImageTk.PhotoImage(resized)
img = tk.Label(root, image=render, height=20,width=80)
img.image = render
img.place(relx=0.14,rely=0.04,relwidth=0.21,relheight=0.2)

#      - Système d'onglets
onglets = tki.Notebook(root,width='100', height="20", style='TNotebook')   
onglets.place(relx=0,rely=0.25,relwidth=1.05,relheight=0.7)

#        Onglet Acteur
o2 = tki.Frame(onglets,style='fond.TFrame')     
onglets.add(o2, text='Acteur(trice)')    
message2 = tk.Label(o2, bg="black",foreground="white", borderwidth=0 , text="Vous recherchez des informations sur un(e) acteur(rice)? Nous pouvons vous aider!!! ",font=("Ubuntu", 18))
message2.place(relx=0.1,rely=0,relwidth=0.8,relheight=0.1)
resultLabel2 = tk.Label(o2, text="", bg="black",fg="white",activebackground="goldenrod",font=("Ubuntu", 18))
resultLabel2.place(relx=0.1,rely=0.3,relwidth=0.8,relheight=0.4)
button=tk.Button(o2,text="Rechercher", command=fiche_acteur, bg="black",fg="white",activebackground="goldenrod",font=("Ubuntu", 18))
s2= tk.StringVar()
search= tk.Entry(o2, width=110, textvariable=s2,font=("Ubuntu", 22)).place(relx=0.1,rely=0.1,relwidth=0.8,relheight=0.1)
button.place(relx=0.1,rely=0.21,relwidth=0.8,relheight=0.08)

# Instruction pour ouvrir la fenêtre et gestion des modifications 
root.mainloop() 

这段代码运行得很好:)!非常感谢。 当然,您必须导入每个库(tkinter、config、pandas…),并将代码连接到服务器和数据库

相关问题 更多 >