Đây là một ứng dụng tra số điện thoại rất đơn giản, do đó bạn chỉ cần có kiến thức cơ bản về Python để có thể hoàn thành ứng dụng này.
Cách tạo ứng dụng tra số điện thoại
Yêu cầu
§ phone-iso3166
§ pycountry
§ Tkinter
Bạn cần cài đặt các thư viện python ở trên để sử dụng trong ứng dụng này.
Cài đặt
pip install python-tk, phone-iso3166, pycountry
Mình sẽ sử dụng phone-iso3166 để xác định tên viết tắt của quốc gia rồi gán vô biến alpha_2
và pycountry
để xác định tên đầy đủ của quốc gia đó bằng cách sử dụng alpha_2
mà chúng ta đã thu thập được từ phone-iso3166
.
Code mẫu
>>> import pycountry
>>> from phone_iso3166.country import phone_country
>>> code = phone_country("255757295721")
>>> code
'TZ'
>>> pycountry.countries.get(alpha_2 = code)
Country(alpha_2='TZ', alpha_3='TZA', common_name='Tanzania', name='Tanzania, United Republic of', numeric='834', official_name='United Republic of Tanzania')
>>>
Giờ thì chúng ta đã biết cách lấy thông tin quốc gia từ số điện thoại, nhưng ứng dụng này vẫn hoạt động dưới dạng command line. Nên bây giờ, chúng ta sẽ thiết kế GUI cho ứng dụng.
Tạo file app.py
Mở notepad lên tạo file app.py với nội dung bên dưới
import json
import pycountry
from tkinter import Tk, Label, Button, Entry
from phone_iso3166.country import phone_country
class Location_Tracker:
def __init__(self, App):
self.window = App
self.window.title("Phone number Tracker")
self.window.geometry("500x400")
self.window.configure(bg="#3f5efb")
self.window.resizable(False, False)
#___________Application menu_____________
Label(App, text="Enter a phone number",fg="white", font=("Times", 20), bg="#3f5efb").place(x=150,y= 30)
self.phone_number = Entry(App, width=16, font=("Arial", 15), relief="flat")
self.track_button = Button(App, text="Track Country", bg="#22c1c3", relief="sunken")
self.country_label = Label(App,fg="white", font=("Times", 20), bg="#3f5efb")
#___________Place widgets on the window______
self.phone_number.place(x=170, y=120)
self.track_button.place(x=200, y=200)
self.country_label.place(x=100, y=280)
#__________Linking button with countries ________
self.track_button.bind("<Button-1>", self.Track_location)
#255757294146
def Track_location(self,event):
phone_number = self.phone_number.get()
country = "Country is Unknown"
if phone_number:
tracked = pycountry.countries.get(alpha_2=phone_country(phone_number))
print(tracked)
if tracked:
country = tracked.official_name
self.country_label.configure(text=country)
PhoneTracker = Tk()
MyApp = Location_Tracker(PhoneTracker)
PhoneTracker.mainloop()
Để chạy file vừa tạo trên windows, bạn mở cmd lên và gõ lệnh python app.py
để khởi chạy chương trình
Kết quả
Khi bạn nhập số điện thoại vào thì lưu ý số 0 đầu tiên thay bằng 84 nhé, ví dụ: 84304xxxxxx. Sau khi nhập xong, các bạn click Enter là có thể biết số điện thoại đó từ quốc gia nào rồi.
Xong rồi, bạn vừa tạo ứng dụng tra vị trí số điện thoại theo quốc gia của riêng mình rồi đó. Nếu bạn thấy ứng dụng này thú vị thì hãy chia sẽ cho bạn bè nhé.