青亭浅 2024-05-21 17:37 采纳率: 88.2%
浏览 5

python111111


import json
from tkinter import *
from tkinter import ttk

import pymysql


class discussClass():
    def __init__(self, master:Frame):
        self.huatiname = StringVar()
        self.content=StringVar()
        self.master = master
        Label(master, text="这是讨论区管理界面").pack()
        self.creatediscuss()

    def creatediscuss(self):
        self.master.configure(bg="#96CDCD")
        # 创建 Treeview 组件
        columns = ("huati", "neirong")

        self.tree_view = ttk.Treeview(self.master, show='headings', columns=columns, style="Treeview")
        self.tree_view.tag_configure("oddrow", background="#EAEAEA")
        self.tree_view.tag_configure("evenrow", background="#FFFFFF")

        self.tree_view.column("huati", width=80, anchor='center')
        self.tree_view.column("neirong", width=80, anchor='center')


        self.tree_view.heading('huati', text="话题")
        self.tree_view.heading('neirong', text="内容")


        self.tree_view.pack(pady=10, fill=BOTH, expand=True)
        # 创建输入框

        # 创建下拉框
        options= json.loads(open('HUATI.json',mode='r',encoding='utf-8').read())


        self.selected_option = StringVar()

        self.dropdown = ttk.Combobox(self.master, textvariable=self.selected_option, values=options, width=20)
        self.dropdown.pack(side="left", padx=5)
        # 创建输入框
        self.entry = Text(self.master, width=40,height=5)
        self.entry.pack(side="left", padx=5)

        #  创建新建讨论按钮

        new_discussion_button = Button(self.master, text="发布",command=self.fabu)
        new_discussion_button.pack(side=BOTTOM, padx=0, pady=(0, 10))
        #Button.grid(row=0,column=0,columnspan=2,padx=10,pady=10)
       #创建发布按钮


        publish_button = Button(self.master, text="新建话题",command=self.add_discussion)
        publish_button.pack(side=BOTTOM, padx=0, pady=(0, 10))

        show_button = Button(self.master, text="刷新",command=self.show_discussion)
        show_button.pack(side=BOTTOM, padx=0, pady=(0, 10))
        for _ in map(self.tree_view.delete, self.tree_view.get_children("")):
            pass
        conn = pymysql.connect(
            host='localhost',
            user='root',
            password='012977',
            database='SHIXUN'
        )

        cursor = conn.cursor()

        sql = "select * from Discuss"

        cursor.execute(sql)

        rest = cursor.fetchall()
        index = 0
        for i in rest:
            print(i)
            self.tree_view.insert("", index + 1, values=(i[0], i[1]))

    def show_discussion(self):
        self.dropdown['values']=['']

        option = json.loads(open('HUATI.json', mode='r', encoding='utf-8').read())
        self.dropdown['values']=option

        for _ in map(self.tree_view.delete, self.tree_view.get_children("")):
            pass
        conn = pymysql.connect(
            host='localhost',
            user='root',
            password='012977',
            database='SHIXUN'
        )

        cursor = conn.cursor()

        sql = "select * from Discuss"

        cursor.execute(sql)

        rest = cursor.fetchall()
        index = 0
        for i in rest:
            print(i)
            self.tree_view.insert("", index + 1, values=(i[0], i[1]))

    def add_discussion(self):
        root = Tk()
        root.title("新建话题")
        root.geometry("200x200")
        Label(root, text="话题").pack()

        entry = Entry(root, textvariable=self.huatiname)
        entry.pack()

        Button(root, text="提交", command=lambda: self.tijiao(entry.get(), root)).pack(pady=20)

    def tijiao(self, new_topic, root):
        with open("HUATI.json", "r", encoding="utf-8") as file:
            data: list = json.load(file)
            data.append(new_topic)
            print(new_topic)

        with open('HUATI.json', 'w') as file:
            json.dump(data, file, indent=4)

        # 关闭新建话题窗口
        root.destroy()

    def fabu(self):
        a = self.selected_option.get()
        b = self.entry.get("1.0", "end")

        conn = pymysql.connect(
            host='localhost',
            user='root',
            password='012977',
            database='SHIXUN'
        )

        cursor = conn.cursor()

        sql = "insert into Discuss values (%s,%s)"


        cursor.executemany(sql,(a,b))
        # 提交
        conn.commit()
        # 关闭
        conn.close()
        cursor.close()





报错

C:\Users\32756\PycharmProjects\TTK\.venv\Scripts\python.exe C:\Users\32756\PycharmProjects\TTK\SHIXUN\asd.py 
('Python', 'dsasdasdh')
('houjianyu', '听说侯健羽是大傻逼')
('呵呵', '打打')
Exception in Tkinter callback
Traceback (most recent call last):
  File "D:\python39\Lib\tkinter\__init__.py", line 1967, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\32756\PycharmProjects\TTK\SHIXUN\discussClass.py", line 148, in fabu
    cursor.executemany(sql,(a,b))
  File "C:\Users\32756\PycharmProjects\TTK\.venv\Lib\site-packages\pymysql\cursors.py", line 182, in executemany
    return self._do_execute_many(
           ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\32756\PycharmProjects\TTK\.venv\Lib\site-packages\pymysql\cursors.py", line 205, in _do_execute_many
    v = values % escape(next(args), conn)
        ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~
TypeError: not enough arguments for format string

进程已结束,退出代码为 0


  • 写回答

1条回答 默认 最新

  • 阿里嘎多学长 2024-05-21 17:48
    关注

    以下内容由CHATGPT及阿里嘎多学长共同生成、有用望采纳:


    【您想要解决的问题】:您提问的目的是解决在运行Python程序时遇到的一个异常错误。这个错误发生在尝试使用 pymysql 库执行数据库插入操作时,具体表现为 TypeError: not enough arguments for format string

    【问题出现原因】:错误提示 TypeError: not enough arguments for format string 表明在执行 cursor.executemany(sql,(a,b)) 时,传入的参数数量与 SQL 语句中占位符的数量不匹配。在您的 SQL 语句 "insert into Discuss values (%s,%s)" 中有两个占位符 %s,但是 executemany 方法在调用时只提供了一个元组 (a,b),导致参数数量不足。

    【问题解决方案】:要解决这个问题,您需要确保 executemany 方法调用时传入的参数数量与 SQL 语句中的占位符数量一致。在您的代码中,您应该将 executemany 方法的调用参数从 (a,b) 改为 [(a,b)],这样就会正确地传入一个包含单个元素的列表,该元素是一个包含两个参数的元组。

    【提供代码】:以下是修改后的 fabu 方法的代码:

    def fabu(self):
        a = self.selected_option.get()
        b = self.entry.get("1.0", "end").strip()  # 移除可能的空白字符
    
        conn = pymysql.connect(
            host='localhost',
            user='root',
            password='012977',
            database='SHIXUN'
        )
    
        cursor = conn.cursor()
    
        sql = "insert into Discuss values (%s,%s)"
    
        # 注意这里修改为列表包含一个元组
        cursor.executemany(sql, [(a, b)])
        conn.commit()
        conn.close()
        cursor.close()
    

    【代码运行方式】:要运行您的代码,您需要有 Python 环境,并且已经安装了 pymysqltkinter 库。您的代码是一个 GUI 应用程序,因此您需要在支持 GUI 的环境中运行它,比如在本地计算机上。

    【代码预期运行结果】:如果代码修改正确,并且数据库连接和 SQL 语句没有问题,那么程序应该能够正常运行,允许用户通过 GUI 发布新的话题和内容到数据库中。

    【推荐相关链接】:

    1. Python pymysql 文档
    2. Python tkinter 文档
    3. Python JSON 模块文档
    4. Python StringVar 和 Text 变量使用
    5. Python 异常处理
    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 5月21日

悬赏问题

  • ¥15 Stable Diffusion,用Ebsynth utility在视频选帧图重绘,第一步报错,蒙版和帧图没法生成,怎么处理啊
  • ¥15 请把下列每一行代码完整地读懂并注释出来
  • ¥15 pycharm运行main文件,显示没有conda环境
  • ¥15 易优eyoucms关于二级栏目调用的问题
  • ¥15 寻找公式识别开发,自动识别整页文档、图像公式的软件
  • ¥15 为什么eclipse不能再下载了?
  • ¥15 编辑cmake lists 明明写了project项目名,但是还是报错怎么回事
  • ¥15 关于#计算机视觉#的问题:求一份高质量桥梁多病害数据集
  • ¥15 特定网页无法访问,已排除网页问题
  • ¥50 如何将脑的图像投影到颅骨上