import tkinter as tk import mysql.connector from tkinter import messagebox as mb # 连接数据库 mydb = mysql.connector.connect( host="localhost", user="root", password="kk", database="c" ) # 创建游标 mycursor = mydb.cursor() # 创建GUI窗口 root = tk.Tk() root.title("MySQL数据库查询") # 创建文本框和标签 query_label = tk.Label(root, text="查询语句:") query_label.grid(row=0, column=0) query_entry = tk.Entry(root) query_entry.grid(row=0, column=1) # 创建按钮 search_button = tk.Button(root, text="查询", command=search) search_button.grid(row=1, column=0) # 创建结果标签 result_label = tk.Label(root, text="") result_label.grid(row=2, column=0, columnspan=2) # 查询函数 def search(): # 获取查询语句 query = query_entry.get() # 执行查询 mycursor.execute(query) result = mycursor.fetchall() # 在结果标签中显示结果 result_label.config(text=result)
时间: 2024-01-14 11:04:46 浏览: 140
Thank you for providing the code. The issue you are encountering is due to the fact that the `search` function has not been defined before it is called in the `search_button` command. To resolve this issue, you can define the `search` function before the `search_button` widget is created. Here is the updated code:
```
import tkinter as tk
import mysql.connector
from tkinter import messagebox as mb
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="kk",
database="c"
)
# 创建游标
mycursor = mydb.cursor()
# 创建GUI窗口
root = tk.Tk()
root.title("MySQL数据库查询")
# 创建文本框和标签
query_label = tk.Label(root, text="查询语句:")
query_label.grid(row=0, column=0)
query_entry = tk.Entry(root)
query_entry.grid(row=0, column=1)
# 查询函数
def search():
# 获取查询语句
query = query_entry.get()
# 执行查询
mycursor.execute(query)
result = mycursor.fetchall()
# 在结果标签中显示结果
result_label.config(text=result)
# 创建按钮
search_button = tk.Button(root, text="查询", command=search)
search_button.grid(row=1, column=0)
# 创建结果标签
result_label = tk.Label(root, text="")
result_label.grid(row=2, column=0, columnspan=2)
# 运行GUI
root.mainloop()
```
I hope this helps! Let me know if you have any further questions.
阅读全文