Advertisement
cgfixit

Initial working tkinter wiki search (find better use case and if cool add to github

Apr 6th, 2025
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | Software | 0 0
  1. import tkinter as tk  
  2. import wikipedia  
  3.  
  4. def search_wikipedia(event=None):  
  5.     """Retrieve user query from a Text widget and display the Wikipedia summary."""  
  6.     query = query_text.get("1.0", tk.END).strip()  
  7.     result_text.delete("1.0", tk.END)  
  8.  
  9.     if not query:  
  10.         result_text.insert("1.0", "Please enter a search term.")  
  11.         return  
  12.  
  13.     try:  
  14.         # Get Wikipedia summary for the entered query  
  15.         summary = wikipedia.summary(query, sentences=50)  
  16.         result_text.insert("1.0", summary)  
  17.     except wikipedia.exceptions.DisambiguationError as e:  
  18.         result_text.insert("1.0", f"Disambiguation error: {e}")  
  19.     except wikipedia.exceptions.PageError:  
  20.         result_text.insert("1.0", "No page found for your query.")  
  21.     except Exception as e:  
  22.         result_text.insert("1.0", f"An unexpected error occurred: {e}")  
  23.  
  24. # Main window  
  25. root = tk.Tk()  
  26. root.title("WikiSearch")  
  27. root.geometry("600x700")  
  28.  
  29. # Frame for input and button  
  30. frame = tk.Frame(root)  
  31. frame.pack(pady=10)  
  32.  
  33. # Create a Text widget for user query  
  34. query_text = tk.Text(frame, width=60, height=8)  
  35. query_text.pack()  
  36.  
  37. # Bind "Enter" key to the search function  
  38. query_text.bind("<Return>", search_wikipedia)  
  39.  
  40. # Create a button to initiate the search  
  41. search_button = tk.Button(frame, text="Search", command=search_wikipedia)  
  42. search_button.pack(pady=5)  
  43.  
  44. # Text widget to display search results  
  45. result_text = tk.Text(root, wrap=tk.WORD, width=70, height=30)  
  46. result_text.pack(pady=10)  
  47.  
  48. # Start the mainloop  
  49. root.mainloop()  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement