需要使用 Tkinter 和 Python 为 km 或 mi 创建选项

Posted

技术标签:

【中文标题】需要使用 Tkinter 和 Python 为 km 或 mi 创建选项【英文标题】:Need to create option for km or mi using Tkinter and Python 【发布时间】:2021-03-07 23:15:51 【问题描述】:

所以下面我找到并修改了一个代码,用于计算两个位置之间的距离。我正在为简单的用户输入创建一个 GUI。一切都按预期工作,但如果我能完成两件事,那将是一个奖励。

    有一个切换或选择可以让我以 KM 或 Mi 显示距离

    有什么办法可以将输出四舍五入,使其小数点后没有那么多数字?

我假设它必须是基于对象选择的某种类型的变量?

# import modules 
from tkinter import *
from geopy.geocoders import Nominatim 
from geopy import distance 

# user defined funtion 
def get_dis(): 
  try: 
      
      geolocator = Nominatim(user_agent="geoapiExercises") 
      
      place1 = geolocator.geocode(str(e1.get())) 
      place2 = geolocator.geocode(str(e2.get())) 


      Loc1_lat,Loc1_lon = (place1.latitude),(place1.longitude) 
      Loc2_lat,Loc2_lon = (place2.latitude),(place2.longitude) 

      location1=(Loc1_lat,Loc1_lon) 
      location2=(Loc2_lat,Loc2_lon) 

      res = (str(distance.distance(location1, location2).mi)+" Mi") 

      result.set(res) 
  except: 
      result.set("someting went wrong") 

# object of tkinter 
# with background set to light grey 
master = Tk() 
master.configure(bg='light grey') 
master.title("Find Distance") 

# Variable Classes in tkinter 
result = StringVar(); 


# Creating label for each information 
# name using widget Label 
Label(master, text="Start Location : " , bg = "light grey").grid(row=1, sticky=W) 
Label(master, text="End Location : " , bg = "light grey").grid(row=2, sticky=W) 

Label(master, text="Result :", bg = "light grey").grid(row=3, sticky=W) 

# Creating label for class variable 
# name using widget Entry 
Label(master, text="", textvariable=result,bg = "light grey").grid(row=3,column=1, sticky=W) 


e1 = Entry(master,width = 50) 
e1.grid(row=1, column=1) 
e2 = Entry(master,width = 50) 
e2.grid(row=2, column=1) 

# creating a button using the widget 
b = Button(master, text="Check", command=get_dis, bg = "white") 
b.grid(row=1, column=2,columnspan=2, rowspan=2,padx=5, pady=5,) 

mainloop()

用注释编辑.. 不能圆

import modules from tkinter import * from geopy.geocoders import Nominatim from geopy import distance

用户定义函数 def get_dis():

try: 
      
    geolocator = Nominatim(user_agent="geoapiExercises") 
      
    place1 = geolocator.geocode(str(e1.get())) 
    place2 = geolocator.geocode(str(e2.get())) 


    Loc1_lat,Loc1_lon = (place1.latitude),(place1.longitude) 
    Loc2_lat,Loc2_lon = (place2.latitude),(place2.longitude) 

    location1=(Loc1_lat,Loc1_lon) 
    location2=(Loc2_lat,Loc2_lon) 

    res = (str(distance.distance(location1, location2) .km)+" Km") 

    result.set(res) 
except: 
    result.set("someting went wrong") 

def get_dis():

    if unit.get() == 'mi':
        res = str(round(distance.distance(location1, location2).mi, 2))+" Mi"
    else:
        res = str(round(distance.distance(location1, location2).km, 2))+" km"   

tkinter 的对象

背景设置为浅灰色 master = Tk() master.configure(bg='light gray') master.title("Find Distance")

tkinter 中的变量类结果 = StringVar();标签(master, text="", textvariable=result,bg = "浅灰色").grid(row=4,column=1,

粘性=W)

为每个信息创建标签

name using widget Label Label(master, text="Start Location : " , bg = "light gray").grid(row=1, sticky=W) Label(master, text="End

位置 : " , bg = "浅灰色").grid(row=2,sticky=W) 标签(master, text="距离:", bg = "浅灰色").grid(row=3, 粘性=W)

为类变量创建标签

name using widget Entry Label(master, text="Unit :", bg="light gray").grid(row=3, sticky=W) Label(master, text="Result :", bg =

"浅灰色").grid(row=4,sticky=W) e1 = Entry(master,width = 50) e1.grid(row=1, column=1) e2 = Entry(master,width = 50) e2.grid(row=2, column=1)

f1 = Frame(master) f1.grid(row=3, column=1,sticky=W) unit = StringVar(value="mi") 单选按钮(f1, text="miles", value="mi", variable=unit, bg="浅灰色").pack(side="left") Radiobutton(f1, text="km", value="km", 变量=单位, bg="light 灰色").pack(side="left")

使用小部件创建按钮 b = Button(master, text="Calculate", command=get_dis, bg = "white") b.grid(row=1,

column=2,columnspan=2, rowspan=2,padx=5, pady=5,) mainloop()

【问题讨论】:

请在您的问题中提供正确的格式。这种格式非常不切实际且难以阅读,以至于我们无法修复它。我们无法确定其中一些粗体线是否旨在成为代码中的 cmets。 【参考方案1】:

首先在结果行前添加两个单选按钮:

Label(master, text="Unit :", bg="light gray").grid(row=3, sticky=W)
Label(master, text="Result :", bg = "light grey").grid(row=4, sticky=W) # changed to row 4
...
f1 = Frame(master)
f1.grid(row=3, column=1, sticky=W)
unit = StringVar(value="mi")
Radiobutton(f1, text="miles", value="mi", variable=unit, bg="light gray").pack(side="left")
Radiobutton(f1, text="km", value="km", variable=unit, bg="light gray").pack(side="left")

result = StringVar(); 
Label(master, text="", textvariable=result,bg = "light grey").grid(row=4,column=1, sticky=W) # changed to row 4

然后根据get_dis()里面选择的单位调用对应的函数:

def get_dis():
    try:
        ...
        if unit.get() == 'mi':
            res = str(round(distance.distance(location1, location2).mi, 3))+" Mi"
        else:
            res = str(round(distance.distance(location1, location2).km, 3))+" km"
    ...

请注意,round(..., 3) 用于将结果四舍五入到小数点后 3 位。

【讨论】:

谢谢,我想除了四舍五入之外,我的一切都正常了……似乎根本不想四舍五入 添加了我在上面更新的内容,如果你可以看看【参考方案2】:
# import modules 
from tkinter import *
from geopy.geocoders import Nominatim 
from geopy import distance 
  
# user defined funtion 
def get_dis(): 
     
          
    geolocator = Nominatim(user_agent="geoapiExercises") 
        
    place1 = geolocator.geocode(str(e1.get())) 
    place2 = geolocator.geocode(str(e2.get())) 


    Loc1_lat,Loc1_lon = (place1.latitude),(place1.longitude) 
    Loc2_lat,Loc2_lon = (place2.latitude),(place2.longitude) 

    location1=(Loc1_lat,Loc1_lon) 
    location2=(Loc2_lat,Loc2_lon) 

    res = (str(distance.distance(location1, location2) .km)+" Km") 

    if unit.get() == 'mi':
        res = str(round(distance.distance(location1, location2).mi, 2))+" Mi"
    else:
        res = str(round(distance.distance(location1, location2).km, 2))+" km"

    result.set(res) 
  
# object of tkinter 
# with background set to light grey 
master = Tk() 
master.configure(bg='light grey') 
master.title("Find Distance") 
  
# Variable Classes in tkinter 
result = StringVar(); 
Label(master, text="", textvariable=result,bg = "light grey").grid(row=4,column=1, sticky=W)  
  
# Creating label for each information 
# name using widget Label  
Label(master, text="Start Location : " , bg = "light grey").grid(row=1, sticky=W) 
Label(master, text="End Location : " , bg = "light grey").grid(row=2, sticky=W) 
  
  
# Creating label for class variable 
# name using widget Entry 
Label(master, text="Unit :", bg="light gray").grid(row=3, sticky=W)
Label(master, text="Result :", bg = "light grey").grid(row=4, sticky=W) 
  
  
e1 = Entry(master,width = 50) 
e1.grid(row=1, column=1) 
e2 = Entry(master,width = 50) 
e2.grid(row=2, column=1) 

f1 = Frame(master)
f1.grid(row=3, column=1, sticky=W)
unit = StringVar(value="mi")
Radiobutton(f1, text="miles", value="mi", variable=unit, bg="light gray").pack(side="left")
Radiobutton(f1, text="km", value="km", variable=unit, bg="light gray").pack(side="left")

# creating a button using the widget   
b = Button(master, text="Calculate", command=get_dis, bg = "white") 
b.grid(row=1, column=2,columnspan=2, rowspan=2,padx=5, pady=5,) 
  
mainloop() 

【讨论】:

【参考方案3】:

由于我们已经使用check 按钮获得了其中一个单位的距离......让我们使用它。我们将它的结果转换为另一个。将Check 更改为Distance in miles,为KM 添加了一个新按钮。创建一个将英里转换为公里的函数。然后是调用这两个函数的函数。Two。这将以英里(get_dis)为单位获得距离并转换为公里(km_mi)。结果将没有小数。我用int。如果你想要小数,你可以使用round,如另一个答案中所建议的那样。

from tkinter import *
from geopy.geocoders import Nominatim
from geopy import distance


# user defined function
def get_dis():
    try:
        global res
        geolocator = Nominatim(user_agent="geoapiExercises")

        place1 = geolocator.geocode(str(e1.get()))
        place2 = geolocator.geocode(str(e2.get()))

        Loc1_lat, Loc1_lon = (place1.latitude), (place1.longitude)
        Loc2_lat, Loc2_lon = (place2.latitude), (place2.longitude)

        location1 = (Loc1_lat, Loc1_lon)
        location2 = (Loc2_lat, Loc2_lon)
        res = int(distance.distance(location1, location2).mi)
        return result.set(res)


    except Exception as e:
        print(e)

def km_mki():
    miles = res
    conv_fac = 1.609  # conversion factor
    # calculating how many kilometers
    kilometers = miles * conv_fac
    return result.set(int(kilometers))
def two():
    get_dis()
    km_mki()


# object of tkinter
# with background set to light grey
master = Tk()
master.configure(bg='light grey')
master.title("Find Distance")

# Variable Classes in tkinter
result = StringVar()

# Creating label for each information
# name using widget Label
Label(master, text="Start Location : ", bg="light grey").grid(row=1, sticky=W)
Label(master, text="End Location : ", bg="light grey").grid(row=2, sticky=W)

Label(master, text="Result :", bg="light grey").grid(row=3, sticky=W)

# Creating label for class variable
# name using widget Entry
Label(master, text="", textvariable=result, bg="light grey").grid(row=3, column=1, sticky=W)

e1 = Entry(master, width=50)
e1.grid(row=1, column=1)
e2 = Entry(master, width=50)
e2.grid(row=2, column=1)

# creating a button using the widget
b = Button(master, text="Get distance in Miles", command=get_dis, bg="white")
b.grid(row=1, column=2, columnspan=2, rowspan=2, padx=5, pady=5, )
b1 = Button(master, text="Get distance in Km", command=two, bg="white")
b1.grid(row=3, column=2, columnspan=2, rowspan=3, padx=5, pady=5, )

mainloop()

【讨论】:

请求用户复制粘贴我的代码,请让我知道答案有什么问题。谢谢。

以上是关于需要使用 Tkinter 和 Python 为 km 或 mi 创建选项的主要内容,如果未能解决你的问题,请参考以下文章

无法更改像素本上的 tkinter 字体

Python3 tkinter,怎么在Label/Canvas中插入图片?

python GUI(Tkinter)

使用python3在Raspberry Pi上打开和关闭Tkinter GUI

python3.6.4 tkinter安装

在python tkinter中为事件创建日历视图[关闭]