import MySQLdb import tkinter as tk import subprocess # 创建主窗口 window = tk.Tk() window.title("连接数据库") # 设计窗口大小 width = 400 height = 280 window.geometry(f"{width}x{height}") # 设置窗口位置,使其居中显示 x = int((window.winfo_screenwidth() - width) / 2) y = int((window.winfo_screenheight() - height) / 2) window.geometry(f"+{x}+{y}") # 创建标签和输入框 host_label = tk.Label(window, text="主机名:") host_label.pack() host_entry = tk.Entry(window) host_entry.pack() username_label = tk.Label(window, text="用户名:") username_label.pack() username_entry = tk.Entry(window) username_entry.pack() password_label = tk.Label(window, text="密码:") password_label.pack() # 创建输入框,并将 show 参数设置为 "*" password_entry = tk.Entry(window, show="*") password_entry.pack() database_label = tk.Label(window, text="数据库:") database_label.pack() database_entry = tk.Entry(window) database_entry.pack() # 创建按钮和回调函数 def connect(): host = host_entry.get() username = username_entry.get() password = password_entry.get() database = database_entry.get() # 尝试连接 try: cnx = MySQLdb.connect(host=host, user=username, password=password, database=database) print("连接成功!") window.destroy() subprocess.run(["python", "ces2.py"]) except MySQLdb.Error as err: print(f"连接失败: {err}") window.destroy() subprocess.run(["python", "mysql_err.py"]) connect_button = tk.Button(window, text="连接", height=3, width=10, command=connect) connect_button.pack() # 运行主循环 window.mainloop() 插入路径为D:\python--\python word\py_mysql\背景图.png的背景图
时间: 2024-02-22 08:59:47 浏览: 190
Python:连接mysql数据库的三种方式,mysql.connector, pymysql, MYSQLdb
要在窗口中添加背景图,可以使用 tkinter 的 Canvas 组件和 PIL 库。以下是添加背景图的示例代码:
```
import tkinter as tk
from PIL import ImageTk, Image
# 创建主窗口
window = tk.Tk()
window.title("连接数据库")
# 加载背景图
bg_image = Image.open("D:/python--/python word/py_mysql/背景图.png")
bg_photo = ImageTk.PhotoImage(bg_image)
# 创建 Canvas 组件并添加背景图
canvas = tk.Canvas(window, width=bg_image.width, height=bg_image.height)
canvas.pack(fill="both", expand=True)
canvas.create_image(0, 0, image=bg_photo, anchor="nw")
# 添加其他组件和回调函数
...
# 运行主循环
window.mainloop()
```
在以上代码中,我们首先使用 PIL 库加载背景图并创建了一个 PhotoImage 对象。然后,我们创建了一个 Canvas 组件并将其占满整个窗口,使用 `create_image` 方法将背景图添加到 Canvas 中。最后,我们可以在 Canvas 中添加其他组件和回调函数,与之前的示例代码相同。
阅读全文