Advertisement
here2share

# Tk_replace_label_text.py

Aug 5th, 2022
1,222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.11 KB | None | 0 0
  1. # Tk_replace_label_text.py
  2.  
  3. from tkinter import *
  4.  
  5. root = Tk()
  6. root.title('Tk_replace_label_text')
  7.  
  8. canvas = Canvas(root, width=400, height=100)
  9. canvas.pack()
  10.  
  11. sample_list = 'this is a sample list of words for the pop up menu'.split()
  12.  
  13. hypertext_word = 'click this text to open the menu'
  14.  
  15. menu = Menu(root, tearoff=0)
  16. for word in sample_list:
  17.     menu.add_command(label=word)
  18.  
  19. text_label = Label(root, text='')
  20. text_label.place(x=0, y=10, width=400)
  21.  
  22. def show_menu(event):
  23.     menu.post(text_label.winfo_rootx()+300, int(menu.winfo_height()))
  24.  
  25. def target_text(selected):
  26.     global text_2_change
  27.     text_2_change = Label(text_label, text=selected, fg='blue', cursor='hand2')
  28.     text_2_change.place(x=10)
  29.     text_2_change.bind('<Button-1>', show_menu)
  30.    
  31. target_text(hypertext_word)
  32.  
  33. def menucallback(event): # hacked solution
  34.     index = root.call(event.widget, "index","active")
  35.     selected = menu.entrycget(index, 'label')
  36.     if selected:
  37.         try:
  38.             text_2_change.destroy()
  39.         except:
  40.             0
  41.         target_text(selected)
  42.  
  43.  
  44. text_label.bind('<Button-1>', show_menu)
  45. menu.bind('<<MenuSelect>>', menucallback)
  46.  
  47. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement