ZX0228 发表于 2024-6-12 11:36

tkinter界面问题求助

各位大佬,第一次写GUI界面用tk不太会,想调整下搜索结果显示界面及最下方的统计显示位置,问过AI了,每次改的都不尽人意。有没有大佬帮忙指导下
import tkinter as tk
from tkinter import messagebox, scrolledtext, filedialog
import pandas as pd
import requests
import json
def search_poi(keyword, city, api_key, page_size=25, max_pages=100):
    url = "http://restapi.amap.com/v3/place/text"
    all_pois = []
    seen = set()
    offset = 0

    try:
      for page in range(1, max_pages + 1):
            params = {
                'key': api_key,
                'keywords': keyword,
                'city': city,
                'output': 'json',
                'extensions': 'all',
                'offset': offset,
                'limit': page_size
            }

            response = requests.get(url, params=params)
            response.raise_for_status()

            result = response.json()
            if result['status'] != '1':
                if 'INVALID_USER_KEY' in result['info']:
                  raise ValueError("无效的API密钥,请检查您的密钥设置。")
                else:
                  raise ValueError(result['info'])

            # 将每个POI的名称和地址组合成元组,用于去重
            for poi in result.get('pois', []):
                poi_tuple = (poi['name'], poi['address'])
                if poi_tuple not in seen:
                  seen.add(poi_tuple)
                  all_pois.append(poi)

            if not result.get('pois'):
                break

            offset += page_size

    except requests.RequestException as e:
      messagebox.showerror("网络错误", f"网络请求失败: {e}")
    except ValueError as ve:
      messagebox.showerror("错误", str(ve))
    except Exception as e:
      messagebox.showerror("未知错误", str(e))

    return all_pois
def on_search_button_click():
    keyword = entry_keyword.get()
    city = entry_city.get()
    if not keyword or not city:
      messagebox.showerror("错误", "请填写关键字和城市!")
      return
    try:
      pois = search_poi(keyword, city, api_key)
      if pois:
            display_pois(pois)
            update_counts(pois)
      else:
            messagebox.showinfo("提示", "未找到匹配的POI信息。")
    except Exception as e:
      messagebox.showerror("错误", str(e))


def display_pois(pois):
    text_widget.delete('1.0', tk.END)
    text_widget.insert(tk.END, "网点名称\t地址\n")
    for poi in pois:
      text_widget.insert(tk.END, f"{poi['name']}\t{poi['address']}\n")


def update_counts(pois):
    # 初始化计数器
    counts = {'中国石油': 0, '中国石化': 0, '兵团石油': 0, '其他': 0}

    # 遍历POI列表进行计数
    for poi in pois:
      name = poi.get('name', '').strip()
      if '中国石油' in name:
            counts['中国石油'] += 1
      elif '中国石化' in name:
            counts['中国石化'] += 1
      elif '兵团石油' in name:
            counts['兵团石油'] += 1
      else:
            counts['其他'] += 1


    total_count = sum(counts.values())
    label_total.config(text=f"总共搜索到 {total_count} 条数据")
    label_china_oil.config(text=f"{counts['中国石油']}")
    label_china_petrochemical.config(text=f"{counts['中国石化']}")
    label_bingtuan_oil.config(text=f"{counts['兵团石油']}")
    label_other.config(text=f" {counts['其他']}")


def on_export_button_click():
    poi_list = text_widget.get("1.0", tk.END).splitlines()# 跳过标题行
    poi_data =
    if poi_data:
      df = pd.DataFrame(poi_data, columns=['网点名称', '地址'])
      file_path = filedialog.asksaveasfilename(defaultextension=".xlsx")
      if file_path:
            df.to_excel(file_path, index=False)
            messagebox.showinfo("成功", "导出完成!")
      else:
            messagebox.showinfo("取消", "导出操作被取消。")
    else:
      messagebox.showerror("错误", "没有数据可以导出。")


api_key = "XXXXXXXXXXXXXXX"

root = tk.Tk()
root.geometry("800x600+630+80")
root.title("加油站POI搜索")

frame_search = tk.Frame(root)
frame_search.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)


label_keyword = tk.Label(frame_search, text="关键字:")
label_keyword.pack(side=tk.LEFT)
entry_keyword = tk.Entry(frame_search, width=20)
entry_keyword.pack(side=tk.LEFT, padx=(0, 5))

label_city = tk.Label(frame_search, text="城市:")
label_city.pack(side=tk.LEFT, padx=(5, 0))

entry_city = tk.Entry(frame_search, width=20)
entry_city.pack(side=tk.LEFT)


search_button = tk.Button(frame_search, text="搜索POI", command=on_search_button_click)
search_button.pack(side=tk.LEFT, padx=5)

export_button = tk.Button(frame_search, text="导出到Excel", command=on_export_button_click)
export_button.pack(side=tk.LEFT, padx=5)

frame_results = tk.Frame(root)
frame_results.pack(fill=tk.BOTH, expand=True)

scrollbar = tk.Scrollbar(frame_results)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

text_widget = scrolledtext.ScrolledText(frame_results, wrap=tk.WORD, width=40, height=10, yscrollcommand=scrollbar.set)
text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.config(command=text_widget.yview)

frame_counts = tk.Frame(frame_results)
frame_counts.pack(side=tk.BOTTOM, fill=tk.X, padx=5, pady=5)

label_total = tk.Label(frame_counts, text="")
label_total.pack(side=tk.LEFT)

tk.Label(frame_counts, text="中国石油: ").pack(side=tk.LEFT, padx=5)
label_china_oil = tk.Label(frame_counts, text="")
label_china_oil.pack(side=tk.LEFT)

tk.Label(frame_counts, text="中国石化: ").pack(side=tk.LEFT, padx=5)
label_china_petrochemical = tk.Label(frame_counts, text="")
label_china_petrochemical.pack(side=tk.LEFT)

tk.Label(frame_counts, text="兵团石油: ").pack(side=tk.LEFT, padx=5)
label_bingtuan_oil = tk.Label(frame_counts, text="")
label_bingtuan_oil.pack(side=tk.LEFT)

tk.Label(frame_counts, text="其他: ").pack(side=tk.LEFT, padx=5)
label_other = tk.Label(frame_counts, text="")
label_other.pack(side=tk.LEFT)

root.mainloop()

lisongmei 发表于 2024-6-12 13:44

曾经学过一会,但全忘了,翻了5分钟笔记,用PLACE布局吧,pack感觉不好用:Dweeqw

头脑发热的少年 发表于 2024-6-12 14:41

亲,这边建议你使用pyside呢,

zjl3480 发表于 2024-6-12 15:15


这样应该可以了
api_key = "XXXXXXXXXXXXXXX"

root = tk.Tk()
root.geometry("800x600+630+80")
root.title("加油站POI搜索")

frame_search = tk.Frame(root)
frame_search.grid(row=0, column=0, sticky='ew', padx=5, pady=5)

label_keyword = tk.Label(frame_search, text="关键字:")
label_keyword.grid(row=0, column=0, sticky='w')

entry_keyword = tk.Entry(frame_search, width=20)
entry_keyword.grid(row=0, column=1, padx=(0, 5))

label_city = tk.Label(frame_search, text="城市:")
label_city.grid(row=0, column=2)

entry_city = tk.Entry(frame_search, width=20)
entry_city.grid(row=0, column=3)

search_button = tk.Button(frame_search, text="搜索POI", command=on_search_button_click)
search_button.grid(row=0, column=4, padx=5)

export_button = tk.Button(frame_search, text="导出到Excel", command=on_export_button_click)
export_button.grid(row=0, column=5, padx=5)

text_widget = scrolledtext.ScrolledText(root, wrap=tk.WORD)
text_widget.grid(row=1, column=0, sticky='nsew', padx=5, pady=5)
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(0, weight=1)

frame_counts = tk.Frame(root)
frame_counts.grid(row=2, column=0, sticky='ew')
root.grid_rowconfigure(2, weight=0)


label_total = tk.Label(frame_counts, text="")
label_total.grid(row=0, column=0, columnspan=2, sticky='e')

tk.Label(frame_counts, text="中国石油: ").grid(row=0, column=2)
label_china_oil = tk.Label(frame_counts, text="")
label_china_oil.grid(row=0, column=3)

tk.Label(frame_counts, text="中国石化: ").grid(row=0, column=4)
label_china_petrochemical = tk.Label(frame_counts, text="")
label_china_petrochemical.grid(row=0, column=5)

tk.Label(frame_counts, text="兵团石油: ").grid(row=0, column=6)
label_bingtuan_oil = tk.Label(frame_counts, text="")
label_bingtuan_oil.grid(row=0, column=7)

tk.Label(frame_counts, text="其他: ").grid(row=0, column=8)
label_other = tk.Label(frame_counts, text="")
label_other.grid(row=0, column=9)

root.mainloop()

照片依旧 发表于 2024-6-12 15:33

建议换一个库,tkinter不是很好用功能相对简陋,wx或者qt相对好一点。

ZX0228 发表于 2024-6-12 15:36

zjl3480 发表于 2024-6-12 15:15
这样应该可以了
api_key = "XXXXXXXXXXXXXXX"



{:1_921:}谢大佬,
页: [1]
查看完整版本: tkinter界面问题求助