使用链接到 google 地方咨询功能的按钮创建 Tkinter 界面

Create a Tkinter interfac with a button linked to a google places consult function

这段代码是我写的。将 google-maps-api 信息获取到结构化 CSV 文件的工作非常完美:

def getPlaces(location,radius,i,j,k):
    url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+location+"&radius="+radius
    r = requests.get(url+"&types="+"establishment"+"&key="+API)
    response = r.json()
    results = []
    for result in response['results']:
        results.append(result)
    if len(results)<20:
        print('next type')
    return results

它应该return一个json结构:

[{'geometry': {'location': {'lat': -1.526394, 'lng': -78.001286},
'viewport': {'northeast': {'lat': -1.525045019708498, 'lng': -77.99993701970848}, 'southwest': {'lat': -1.527742980291502, 'lng': -78.0026349802915}}}, 'icon': 'https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png', 'id': '69e54af1e371137add1acca484b0fc7845184b1f', 'name': 'zoorefugio tarqui', 'opening_hours': {'open_now': True, 'weekday_text': []}, 'photos': [{'height': 2592, 'html_attributions': ['Franklin Guaman'], 'photo_reference': 'CmRaAAAAWBe-CXcL8f52LopjP_nvS1BvtIrdhK5-XvYwG2oA9tS2oh3dzuyYlVIg_3z72mhf2NZ7Sv2S38UDm8J5lZkiDtC8hTZsLT9phKOA54i_W-DcuZQVnESGvHAizXRV4t1xEhAEx9KPnD5vjORlqLdVtrJEGhQ6YnBLp1P0GITIr8fEUB6a5WducA', 'width': 4608}], 'place_id': 'ChIJRePuE4re05ERVpc1cgpIogQ', 'rating': 4.5, 'reference': 'CmRRAAAA0MBgQLzubtDJGAJGZDW7wuZFujGVq6bNQNAvsMj5mQOVV9mNfmxKxlACFuC1UL8exB2AEtj63yiraasnbAHFf7TmBSd7bLZ1b_HFd2H6Z5JbJ5sIAS1CA3dQ-lWsMAIAEhBVgsIvcMM2aPdCUU6739lzGhT7o9nZun5tM0klSzyQf8nNhkGDzg', 'scope': 'GOOGLE', 'types': ['zoo', 'bar', 'restaurant',
'food', 'point_of_interest', 'establishment'], 'vicinity': 'Parroquia Tarqui, 160150 Puyo, Ecuador, Puyo'}]

下一个代码会将 json 转换为一个框架并将其作为 CSV 文件保存到一个文件中:

def placesCsv(location,radius,i,j,k):
    places_jn=json_normalize(getPlaces(location,radius,i,j,k))
    s = places_jn.apply(lambda x: pd.Series(x['types']),axis=1).stack().reset_index(level=1, drop=True)
    s.name = 'types'
    places_df.drop_duplicates(subset=['id','types'], keep='first', inplace=True)
    places_df.to_csv('google_places'+str(location)+'.csv')

我得到了这些结果,它们以 csv 格式保存在设置文件中:

> next type 
> next type amusement_park API: 20
> 2 20 2  
> next type aquarium API: 20
> 2 20 3  
> Did not find results for the type aquarium 
> next type art_gallery API: 20
> 2 20 4  
> Did not find results for the type art_gallery 
> this was the final type

如您所见,它没有 return 前两个类型 airport 和 accounting,因为它没有找到任何一个。然后它没有找到任何 art_gallery,这就是为什么它 returns "Did not find results for the type art_gallery".

现在,我正在尝试创建一个 Tkinter 界面来使 API 咨询像:

from tkinter import *
from functools import partial
def get_entry_fields():
   lat=e1.get()
   lng=e2.get()
   latlng=str(lat)+','+str(lng)

def radius():
    radius=str(e3.get())

def look():
    print("Single Click, Button-l") 
    places=placesCsv(location=str(get_entry_fields()),
                     radius=str(radius()),
                     i=0,
                     j=10,
                     k=0)

def quit():                           
    print("Right Click, so let's stop") 
    widget.destroy

master = Tk()
Label(master, text="lat").grid(row=0)
Label(master, text="lng").grid(row=1)
Label(master, text="radius").grid(row=2)

e1=Entry(master)
e2=Entry(master)
e3=Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)

Button(master, text='Quit', command=master.destroy).grid(row=4, column=2, sticky=W, pady=4)
Button(master, text='Show', command=look).grid(row=4, column=0, sticky=W, pady=4)
mainloop( )

当我 运行 通过具有相同纬度、经度和半径的接口的函数时,输出如下所示:

> Single Click, Button-l
> next type
> next type amusement_park10
> 0 10 2
> next type aquarium10
> 0 10 3
> next type art_gallery10
> 0 10 4
> this was the final type

如您所见,它没有 return 前两种类型 ariport 和 accounting,因为它没有找到它们中的任何一种。它找到了其他地方,但列表 "results" 的长度为零。然后 json 文件没有任何类型列表。所以我得到这个错误:

> Exception in Tkinter callback
> Traceback (most recent call last):   File
> "C:\Users\NA401134\AppData\Local\Continuum\anaconda3\lib\tkinter\__init__.py",
> line 1699, in __call__
>     return self.func(*args)   File "<ipython-input-50-8e3a3f48613d>", line 32, in look
>     k=0)   File "<ipython-input-42-4681f83b6314>", line 5, in placesCsv
>     places_df=places_jn.drop('types', axis=1).join(s)   File "C:\Users\NA401134\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py",
> line 2161, in drop
>     new_axis = axis.drop(labels, errors=errors)   File >"C:\Users\NA401134\AppData\Local\Continuum\anaconda3\lib\site->packages\pandas\core\indexes\base.py",
> line 3624, in drop
>     labels[mask]) ValueError: labels ['types'] not contained in axis

如您所见,我无法将 json 转换为框架,因为当通过界面进行咨询时,类型中没有结果。

代码如下:

def get_entry_fields(lat,lng):
   latlng=str(lat)+','+str(lng)
   return(latlng)


def look():
    print("Single Click, Button-l") 
    places=PlacesCsv(
            location=get_entry_fields(
                    lat=e1.get(),
                    lng=e2.get()
                    ),
                    radius=str(
                            e3.get()
                            ),
                     i=0,
                     j=100,
                     k=0)

def quit():                           
    print("Right Click, so let's stop") 
    widget.destroy()

master = Tk()
Label(master, text="lat").grid(row=0)
Label(master, text="lng").grid(row=1)
Label(master, text="radius").grid(row=2)

e1=Entry(master)
e2=Entry(master)
e3=Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)

Button(master, text='Quit', command=master.destroy).grid(row=4, column=2, sticky=W, pady=4)
Button(master, text='Show', command=look).grid(row=4, column=0, sticky=W, pady=4)
mainloop( )