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

Tkinter登录程序中无法比较JSON文件内容的问题求助

问题排查与修复方案

以下是修正后的完整代码:

from tkinter import *
import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image
import json
import requests

# 获取并解析远程JSON数据
response = requests.get('http://elbekjk.com/ids.json')
ids_list = response.json()

root = Tk()
root.title('Data Discovery Lab')
root.iconbitmap('c://DataDiscoveryLab/images/datadiscoverylab_favicon_142c61.ico')
root.geometry('300x450')
root.resizable(False, False)

myblue = "#142c61"
white = '#ffffff'
root.configure(background = myblue)
frame = Frame(root)
frame.pack()
canvas = Canvas(frame, bg=myblue, width=300, height=450)
canvas.pack()
logo = PhotoImage(file='c://DataDiscoveryLab/images/datadiscoverylab-logo-white-on-transparent-116.png')
canvas.create_image(150,120,image=logo)

# 创建输入组件
username_label = ttk.Label(root, text="Username:")
username_label.place(relx = .2, rely = .5, anchor = CENTER)
username_entry = ttk.Entry(root)
username_entry.place(relx = .6, rely = .5, anchor = CENTER)

password_label = ttk.Label(root, text="Password:")
password_label.place(relx = .2, rely = .6, anchor = CENTER)
password_entry = ttk.Entry(root,  show="*")
password_entry.place(relx = .6, rely = .6, anchor = CENTER)

def check_id():
    # 点击按钮时获取用户最新输入的内容
    input_username = username_entry.get().strip()
    input_password = password_entry.get().strip()
    
    # 构造用户凭证字典
    user_cred = {"username": input_username, "password": input_password}
    
    # 检查凭证是否在远程获取的列表中
    if user_cred in ids_list:
        print('ID found')
    else:
        print('ID not found')

login_button = ttk.Button(root, text="Login", command=check_id)
login_button.place(relx = .68, rely = .7, anchor = CENTER)

root.mainloop()

核心问题与解决说明

  • JSON数据解析错误:原代码仅保存了requests响应对象,未解析实际JSON内容。修正为response.json()直接将响应内容解析为Python列表,才能进行后续存在性检查。
  • 输入内容获取时机错误:原代码在窗口初始化时就调用get(),此时用户未输入任何内容,得到空字符串。修正为在check_id函数内获取输入,确保每次点击按钮时拿到最新输入。
  • 凭证匹配逻辑错误:原代码将字典转成JSON字符串匹配,易因格式差异(如空格、键顺序)导致失败。直接用Python字典与解析后的列表字典比较,逻辑更可靠简洁。

内容的提问来源于stack exchange,提问作者Elbek Keskinoglu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:42:04