You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python CustomTkinter搜索按钮失效问题求助

搜索按钮失效问题修复方案

问题根源

你的搜索功能完全无法工作,主要是以下几个错误导致:

  1. openpyxl API使用错误:xl.cell.read_only(sheet,column = ['A'])是完全错误的用法,openpyxl没有这种调用方式,你无法直接将输入字符串和整列对象做相等比较。
  2. 未遍历单元格检查匹配:你需要遍历A列的每一个单元格,逐个对比是否和输入的ID一致。
  3. 需求实现偏差:原代码找到匹配后是添加标签,但你需求是弹出提示框,逻辑不符。
  4. 小语法问题:FontBig = font=("Arial",25)写法不规范,应直接赋值元组。

修正后的完整代码

import tkinter
from tkinter import messagebox
import openpyxl as xl
import customtkinter

app = customtkinter.CTk()
app.geometry("1280x720")
app.title("Panelmatica")
customtkinter.set_appearance_mode("dark")
# 修正字体赋值的语法问题
FontBig = ("Arial",25)
FontMed = ("Arial",20)

def search():
    try:
        # 只读模式加载Excel,提升性能
        file = xl.load_workbook('Data.xlsx', read_only=True)
        sheet = file["Sheet1"]
        search_id = Search_Entry.get().strip()  # 去除输入的首尾空格
        
        # 遍历A列所有单元格(values_only=True直接获取单元格值)
        for row in sheet.iter_rows(min_row=1, max_row=sheet.max_row, min_col=1, max_col=1, values_only=True):
            # 转字符串并去空格,避免类型或空格导致的匹配失败
            cell_id = str(row[0]).strip()
            if cell_id == search_id:
                messagebox.showinfo(title="Success", message="success")
                file.close()
                return
        # 遍历完未找到匹配ID的情况
        messagebox.showwarning(title="提示", message="未找到该ID")
        file.close()
    except FileNotFoundError:
        messagebox.showerror(title="错误", message="找不到Data.xlsx文件")
    except Exception as e:
        messagebox.showerror(title="错误", message=f"搜索失败:{str(e)}")

def Add():
    try:
        file=xl.load_workbook('Data.xlsx')
        sheet=file["Sheet1"]
        ID_Code =Add_ID_Entry.get().strip()
        Location=Add_Location_Entry.get().strip()
        if not ID_Code or not Location:
            messagebox.showwarning(title="提示", message="ID和位置不能为空")
            return
        sheet.cell(column=1,row=sheet.max_row +1,value =ID_Code)
        sheet.cell(column=2,row=sheet.max_row,value =Location)
        file.save('Data.xlsx')
        messagebox.showinfo(title="Success",message="success")
    except FileNotFoundError:
        messagebox.showerror(title="错误", message="找不到Data.xlsx文件")
    except Exception as e:
        messagebox.showerror(title="错误", message=f"添加失败:{str(e)}")

Create_Button = customtkinter.CTkButton(master=app,text ="Add",width=200,height=100,font=FontBig,fg_color="#2e2e2e",command=Add)
Create_Button.place(x=10,y=555)

Search_Button = customtkinter.CTkButton(master=app,text="Search",width=200,height=100,font=FontBig,fg_color="#2e2e2e",command=search)
Search_Button.place(x=10,y=200)

ElectricPanel=customtkinter.CTkFrame(master=app,width=200,height=600,fg_color="#451411")
ElectricPanel.place(x=320,y=50)

M1_Panel=customtkinter.CTkFrame(master=app,width=200,height=600,fg_color="#383838")
M1_Panel.place(x=550,y=50)

M2_Panel=customtkinter.CTkFrame(master=app,width=200,height=600,fg_color="#383838")
M2_Panel.place(x=780,y=50)

M3_Panel=customtkinter.CTkFrame(master=app,width=200,height=600,fg_color="#383838")
M3_Panel.place(x=1010,y=50)

ElectricText=customtkinter.CTkLabel(master=app,text="Panel Electrical Tools",font=FontMed)
ElectricText.place(x=320,y=20)

MechText1=customtkinter.CTkLabel(master=app,text="Panel Mechanical Tools",font=FontMed)
MechText1.place(x=550,y=20)

MechText2=customtkinter.CTkLabel(master=app,text="Panel Mechanical Tools",font=FontMed)
MechText2.place(x=780,y=20)

MechText3=customtkinter.CTkLabel(master=app,text="Panel Mechanical Tools",font=FontMed)
MechText3.place(x=1010,y=20)

SearchText= customtkinter.CTkLabel(master=app,text="Search:",font= FontMed)
SearchText.place(x=15,y = 150)

IDText=customtkinter.CTkLabel(app,text="ID:",font=FontMed)
IDText.place(x=15,y=500)

PLText=customtkinter.CTkLabel(app,text="Location:",font=FontMed)
PLText.place(x=15,y=450)

Search_Entry = customtkinter.CTkEntry(app)
Search_Entry.place(x= 100, y=150)

Add_ID_Entry = customtkinter.CTkEntry(app)
Add_ID_Entry.place(x= 50, y=500)
Add_Location_Entry = customtkinter.CTkEntry(app)
Add_Location_Entry.place(x= 100, y=450)

app.mainloop()

额外优化说明

  1. 给Add函数增加了空值检查和异常捕获,避免因空输入或文件问题崩溃。
  2. 给重复的标签变量重命名(原代码都用ElectricText),代码更规范。
  3. 使用read_only=True加载Excel搜索,提升大文件的处理速度。
  4. 去除输入内容的首尾空格,避免因用户输入空格导致匹配失败。

内容的提问来源于stack exchange,提问作者Alex M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 08:35:09