Advertisement
here2share

# tk_WUTYEWCIE.py To Build The Ultimate Python Project

Sep 19th, 2024
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.06 KB | None | 0 0
  1. # tk_WUTYEWCIE.py
  2.  
  3. '''
  4. About: A Community Python Project To Make Python Programming The Easiest As Possible To Do
  5. .
  6. At the moment... this project apparently needs to be in a better "partnership" filtering social platform for which each of us can block out anybody in many various ways.
  7. '''
  8.  
  9. import tkinter as tk
  10. from tkinter import *
  11. from tkinter import ttk, colorchooser, font
  12. from random import choice, randint
  13. import itertools
  14. import re
  15.  
  16. root = tk.Tk()
  17. root.title("Widget Demo")
  18. root.geometry(f"+{100}+{5}")
  19. root.resizable(False, False)
  20. root.attributes('-topmost', True)
  21.  
  22. def pick_color(color_var):
  23.     color = colorchooser.askcolor()[1]
  24.     if color:
  25.         color_var.set(color)
  26.  
  27. def oMenu(label, v1, v2, cmd=None):
  28.     try:
  29.         vals = [v2[0]] + v2
  30.     except:
  31.         vals = []
  32.     return ttk.OptionMenu(label, v1, *vals, command=cmd)
  33.  
  34. def xMenu(label, v1, v2, cmd=None):
  35.     geom = root.geometry()     
  36.     w, h, x, y = map(int, re.findall(r"(\d+)", geom))
  37.     label.grid(row=r, column=1)
  38.     menu_frame = Frame(label)
  39.     menu_frame.grid(row=rrr(), column=1, sticky=E)
  40.     menu_window = Toplevel(label)
  41.     menu_window.overrideredirect(True)
  42.     menu_window.resizable(False, False)
  43.     root.attributes('-topmost', False)
  44.     menu_window.attributes('-topmost', True)
  45.        
  46.     listbox_frame = Frame(menu_window)
  47.     listbox_frame.pack()
  48.  
  49.     scrollbar = Scrollbar(listbox_frame, orient=tk.VERTICAL)
  50.     listbox = Listbox(listbox_frame, height=42)
  51.     scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
  52.  
  53.     listbox.config(yscrollcommand=scrollbar.set)
  54.     listbox.pack(side=tk.LEFT, fill=tk.BOTH)
  55.     scrollbar.config(command=listbox.yview)
  56.  
  57.     for item in v2:
  58.         listbox.insert(END, item)
  59.        
  60.     def on_leave(event):
  61.         x = root.winfo_pointerx()
  62.         geom = menu_window.geometry()
  63.         w, h, x2, y2 = map(int, re.findall(r"(\d+)", geom))
  64.         if not (x2 < x < x2 + w + 50):
  65.             menu_window.destroy()
  66.         root.attributes('-topmost', True)
  67.  
  68.     def on_select(event):
  69.         selected = listbox.get(listbox.curselection())
  70.         v1.set(selected)
  71.         menu_window.destroy()
  72.        
  73.     listbox.bind("<Leave>", on_leave)
  74.     listbox.bind('<<ListboxSelect>>', on_select)
  75.     listbox.config(width=30)
  76.    
  77.     menu_window.geometry(f"+{x+80}+{10}")
  78.  
  79. def create_beveled_button(parent, text_var, command):
  80.     label = tk.Label(parent, textvariable=text_var,
  81.                      relief=tk.RAISED, borderwidth=2, padx=5, pady=5,
  82.                      bg="#e1e1e1", fg="#000000")
  83.     label.bind("<Button-1>", command)
  84.     return label
  85.    
  86. def toggle_widgets(widget, target, bit='disabled'):
  87.     if target in str(widget).lower():
  88.         try:
  89.             widget.config(state='!disabled')
  90.         except:
  91.             pass
  92.         if isinstance(widget, Entry):
  93.             widget.delete(0, END)
  94.         elif isinstance(widget, Text):
  95.             widget.delete(1.0, END)
  96.         try:
  97.             widget.config(state=bit)
  98.         except:
  99.             pass
  100.  
  101.     for child in widget.winfo_children():
  102.         toggle_widgets(child, target, bit)
  103.  
  104. def apply_syntax():
  105.     selected = selected_widget.get()
  106.     options = {}
  107.  
  108.     for option in primary_options_list:
  109.         if option in menu_widget:
  110.             option_widget = menu_widget[option]
  111.             if option_label[option].cget('state') != 'disabled':
  112.                 if isinstance(option_widget, ttk.OptionMenu):
  113.                     value_var = next((var for var in menu_sVar.values() if option in var.get()), None)
  114.                     options[option] = value_var.get() if value_var else ""
  115.                 else:
  116.                     try:
  117.                         options[option] = option_widget.get()
  118.                     except:
  119.                         continue
  120.         elif option in option_label:
  121.             option_widget = option_label[option]
  122.             if option_widget.cget('state') != 'disabled':
  123.                 try:
  124.                     options[option] = option_widget.get()
  125.                 except:
  126.                     continue
  127.  
  128.     syntax = f"{selected}(root, " + ", ".join(f"{key}='{val}'" for key, val in options.items() if val) + ")"
  129.     print(syntax)
  130.    
  131. def randomly_create_data(e=None):          
  132.     toggle_widgets(root, "", 'disabled')
  133.     selected_widget_menu.config(state='normal')
  134.     apply_button.config(state='normal')
  135.     x, y = [randint(1, 20) * 5 for i in range(2)]
  136.     width, height = [randint(1, 20) * 5 for i in range(2)]
  137.     options = {
  138.         'x': x,
  139.         'y': y,
  140.         'width': width,
  141.         'height': height,
  142.         'text': ''.join(choice('qwrtypdfghjkzxvbnm') for _ in range(16)),
  143.         'font': choice(font_list),
  144.         'command': choice('copy cut paste exit None'.split()),
  145.         'image': choice('gif jpg png None'.split()),
  146.         'relief': choice(relief_list),
  147.         'state': choice(state_list),
  148.         'justify': choice(justify_list),
  149.         'anchor': choice(anchor_list),
  150.         'fg': '#000000',
  151.         'bg': '#ffffff',
  152.         'padx': '',
  153.         'pady': '',
  154.         'wrap': '',
  155.         'wraplength': ''
  156.     }
  157.  
  158.     selected = selected_widget.get()
  159.     try:
  160.         widget_keys = eval(selected+'().config().keys()')
  161.     except:
  162.         widget_keys = eval(selected+'(root).config().keys()')
  163.  
  164.     for xy in 'xy':
  165.         option_widget = options_label.grid_slaves(row=primary_options_list.index(xy)+1, column=1)[0]
  166.         option_widget.config(state='normal')
  167.         option_widget.delete(0, END)
  168.         option_widget.insert(0, eval(xy))
  169.  
  170.     for option in options:
  171.         option_widget = menu_widget[option]
  172.         try:
  173.             menu_sVar[option].set('...')
  174.         except:
  175.             0
  176.         if option in widget_keys:
  177.             if option in ('font'):
  178.                 menu_widget['size']['state'] = 'normal'
  179.                 menu_sVar['size'].set(choice(size_options))
  180.                 menu_widget['style']['state'] = 'normal'
  181.                 menu_sVar['style'].set(choice(font_styles))
  182.             try:
  183.                 menu_sVar[option].set(options[option])
  184.             except:
  185.                 0
  186.             try:
  187.                 option_label[option].config(state='normal')
  188.             except:
  189.                 0
  190.             try:
  191.                 option_widget.config(state='normal')
  192.                 option_widget.insert(0, options[option])
  193.             except:
  194.                 0
  195.             try:
  196.                 option_widget.set(options[option])
  197.             except:
  198.                 0
  199.         else:
  200.             if option in ('font'):
  201.                 menu_widget['size']['state'] = 'normal'
  202.                 menu_sVar['size'].set('...')
  203.                 menu_widget['style']['state'] = 'normal'
  204.                 menu_sVar['style'].set('...')
  205.  
  206. r = -1
  207. def rrr():
  208.     global r
  209.     r += 1
  210.     return r
  211.  
  212. option_label = {}
  213. menu_sVar = {}
  214. menu_widget = {}
  215.  
  216. font_list = list(font.families())
  217.  
  218. widget_list = [feature for feature in dir(tk) if feature.lower() not in ('image', 'tk', 'ttk')]
  219. widget_list = [feature for feature in widget_list if hasattr(eval(f"tk.{feature}"), 'config')]
  220. widget_list.pop()
  221.  
  222. primary_options_list = '''
  223. x y width height text font image relief state anchor justify padx pady wrap wraplength fg bg command
  224. '''.strip().split()
  225.  
  226. state_list = '''
  227. normal active disabled
  228. '''.strip().split()
  229.  
  230. justify_list = '''
  231. center right left
  232. '''.strip().split()
  233.  
  234. anchor_list = '''
  235. N NE E SE S SW W NW
  236. '''.strip().split()
  237.  
  238. relief_list = '''
  239. FLAT RAISED SUNKEN GROOVE RIDGE
  240. '''.strip().split()
  241.  
  242. primary_options_list = '''
  243. x y width height text font image relief state anchor justify padx pady wrap wraplength fg bg command
  244. '''.strip().split()
  245.  
  246. size_options = list(range(6, 400))
  247.  
  248. font_styles = list(itertools.product(['', 'bold'], ['', 'roman', 'italic']))
  249. font_styles = [f"{weight} {slant}".strip() for weight, slant in font_styles]
  250.  
  251. options_label = LabelFrame(root, text="Selected Widget Options")
  252. options_label.grid(padx=3, pady=5)
  253.  
  254. selected_widget = StringVar(options_label)
  255. selected_widget_menu = oMenu(options_label, selected_widget, widget_list, randomly_create_data)
  256. selected_widget_menu.grid(row=rrr(), column=1, sticky=E)
  257. selected_widget.set('Canvas')
  258.  
  259. for option in primary_options_list:
  260.     option_label[option] = Label(options_label, text=option, fg='red')
  261.     option_label[option].grid(row=rrr(), column=0, sticky=E)
  262.     if option == 'font':
  263.         option_label[option].grid(sticky=W)
  264.         menu_sVar[option] = StringVar(options_label)
  265.         menu_widget[option] = oMenu(options_label, menu_sVar[option], font_list)
  266.         menu_widget[option].grid(row=r, column=0, columnspan=2, sticky=E, padx=(24, 0))
  267.         menu_sVar['size'] = StringVar(options_label)
  268.         menu_widget['size'] = oMenu(options_label, menu_sVar['size'], size_options)
  269.         menu_widget['size'].grid(row=rrr(), column=0, columnspan=2, sticky=W)
  270.         menu_sVar['style'] = StringVar(options_label)
  271.         menu_widget['style'] = oMenu(options_label, menu_sVar['style'], font_styles)
  272.         menu_widget['style'].grid(row=r, column=1, columnspan=2, sticky=E)
  273.     elif option == 'relief':
  274.         menu_sVar[option] = StringVar(options_label)
  275.         menu_widget[option] = oMenu(options_label, menu_sVar[option], relief_list)
  276.         menu_widget[option].grid(row=r, column=1, sticky=E)
  277.     elif option == 'state':
  278.         menu_sVar[option] = StringVar(options_label)
  279.         menu_widget[option] = oMenu(options_label, menu_sVar[option], state_list)
  280.         menu_widget[option].grid(row=r, column=1, sticky=E)
  281.     elif option == 'justify':
  282.         menu_sVar[option] = StringVar(options_label)
  283.         menu_widget[option] = oMenu(options_label, menu_sVar[option], justify_list)
  284.         menu_widget[option].grid(row=r, column=1, sticky=E)
  285.     elif option == 'anchor':
  286.         menu_sVar[option] = StringVar(options_label)
  287.         menu_widget[option] = oMenu(options_label, menu_sVar[option], anchor_list)
  288.         menu_widget[option].grid(row=r, column=1, sticky=E)
  289.     elif option in ['fg', 'bg']:
  290.         menu_widget[option] = Entry(options_label, textvariable=option)
  291.         menu_widget[option].grid(row=r, column=1, padx=2, sticky=W)
  292.         canvas_btn = Canvas(options_label, width=72, height=20)
  293.         canvas_btn.grid(row=r, column=1, padx=2, sticky=E)
  294.         canvas_btn.create_rectangle(0, 0, 72, 20, fill='gray', tag='rectangle')
  295.         canvas_btn.create_text(36, 10, text="Pick Color", fill="white", tag='text', anchor='center')
  296.         canvas_btn.bind('<Button-1>', lambda event, c=menu_widget[option]: pick_color(c))
  297.     else:
  298.         menu_widget[option] = Entry(options_label)
  299.         menu_widget[option].grid(row=r, column=1, padx=2, sticky='ew')
  300.  
  301. xm, ym = 0, 0
  302. def on_pressed(event):
  303.     global xm, ym
  304.     xm, ym = event.x, event.y
  305.  
  306. def on_motion(event):
  307.     x = root.winfo_x() - xm + event.x
  308.     y = root.winfo_y() - ym + event.y
  309.     root.geometry(f"+{x}+{y}")
  310.        
  311. apply_button = Button(options_label, text="Apply", command=apply_syntax)
  312. apply_button.grid(row=rrr(), column=0, sticky='ew')
  313.  
  314. root.bind("<ButtonPress-1>", on_pressed)
  315. root.bind("<B1-Motion>", on_motion)
  316.  
  317. randomly_create_data()
  318. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement