Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_auto_script.py
- import tkinter as tk
- from tkinter import filedialog, colorchooser
- import re
- from PIL import ImageGrab, ImageTk, Image
- import zlib
- import base64
- def create_scrollable_frame(parent):
- canvas = tk.Canvas(parent, bg='black')
- scrollbar = tk.Scrollbar(parent, orient="vertical", command=canvas.yview)
- frame = tk.Frame(canvas)
- frame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
- canvas.create_window((0, 0), window=frame, anchor="nw")
- canvas.configure(yscrollcommand=scrollbar.set)
- canvas.pack(side="left", fill="both", expand=True)
- scrollbar.pack(side="right", fill="y")
- canvas.bind_all("<MouseWheel>", lambda e: canvas.yview_scroll(int(-1*(e.delta/120)), "units"))
- return canvas, frame
- def create_topwindow(title, geometry=None):
- window = tk.Toplevel(root)
- window.title(title)
- if geometry: window.geometry(geometry)
- window.transient(root)
- window.grab_set()
- return window
- def create_label(parent, text, bg, fg, **kwargs):
- label = tk.Label(parent, text=text, bg=bg, fg=fg, bd=0, padx=2, **kwargs)
- label.pack(side=tk.LEFT)
- return label
- def setup_bindings(widget, block_name=None, is_editable=False):
- if is_editable:
- widget.bind("<Button-1>", on_editable_click)
- else:
- widget.bind("<Button-1>", lambda e, name=block_name: toggle_feature(name))
- widget.bind("<Button-3>", show_widget_options_menu)
- # Data Management
- def extract_segment_value(segment, matched_type):
- if matched_type in ('text', 'bg', 'fg', 'append'):
- return segment.split("'")[1]
- elif matched_type in ('x', 'y'):
- return segment.split("=")[1]
- elif matched_type == 'geometry':
- return segment.split("'")[1]
- return segment
- def update_template_block(block_name, old_segment, new_segment):
- for i, line in enumerate(template_blocks[block_name]['lines']):
- if old_segment in line:
- template_blocks[block_name]['lines'][i] = line.replace(old_segment, new_segment)
- break
- template_blocks[block_name]['content'] = '\n'.join(template_blocks[block_name]['lines'])
- def get_block_colors(block_name):
- enabled = template_blocks[block_name]['enabled']
- return ('black', '#009900') if enabled else ('#990000', 'red')
- # Editor Functions
- def create_line_frame(block_name, bg):
- frame = tk.Frame(scrollable_frame, bg=bg, bd=0, relief='flat', width=1400)
- frame.pack(fill=tk.X, expand=True, pady=0)
- frame.block_name = block_name
- setup_bindings(frame, block_name)
- return frame
- def create_segment_label(parent, segment, match, block_name, label_bg, editable_bg):
- if match:
- matched_type = next(k for k,v in match.groupdict().items() if v)
- current_value = extract_segment_value(segment, matched_type)
- label = create_label(parent, segment, editable_bg, 'white')
- label.segment_info = {
- 'full_text': segment,
- 'segment': segment,
- 'current_value': current_value,
- 'type': type_map[matched_type],
- 'block_name': block_name
- }
- return label, True
- return create_label(parent, segment, label_bg, 'white', anchor='w'), False
- def insert_line(text, block_name):
- label_bg, editable_bg = get_block_colors(block_name)
- line_frame = create_line_frame(block_name, label_bg)
- for segment in filter(None, re.split(pattern, text)):
- match = re.fullmatch(pattern, segment)
- label, is_editable = create_segment_label(line_frame, segment, match, block_name, label_bg, editable_bg)
- setup_bindings(label, block_name, is_editable)
- # Picker Dialogs
- def create_picker_window(title, geometry):
- window = create_topwindow(title, geometry)
- window.transient(root)
- window.grab_set()
- return window
- def add_standard_controls(window, callback):
- frame = tk.Frame(window)
- frame.pack(pady=5)
- tk.Label(frame, text="Custom:").pack(side=tk.LEFT)
- entry = tk.Entry(frame, width=30)
- entry.pack(side=tk.LEFT, padx=5)
- tk.Button(frame, text="Apply", command=lambda: [callback(entry.get()), window.destroy()]).pack(side=tk.LEFT)
- return entry
- def show_color_picker(segment_info, label):
- def apply_color(val):
- update_segment(label, val)
- window.destroy()
- window = create_picker_window("Choose Color", "800x400+0+0")
- current_color = segment_info['current_value']
- tk.Label(window, text=f"Current: {current_color}", bg=current_color).pack(pady=10)
- grid_frame = tk.Frame(window)
- grid_frame.pack(pady=2)
- for i, (name, hex_val) in enumerate(colors.items()):
- if i % 8 == 0:
- row_frame = tk.Frame(grid_frame)
- row_frame.pack()
- btn = tk.Button(row_frame, bg=hex_val, width=9, height=1, command=lambda v=hex_val: apply_color(v))
- btn.pack(side=tk.LEFT, padx=5, pady=5)
- entry = add_standard_controls(window, apply_color)
- tk.Button(window, text="System Picker", command=lambda: apply_color(colorchooser.askcolor()[1] or current_color)).pack(pady=10)
- def show_window_size_picker(segment_info, label):
- def apply_size(size):
- update_segment(label, size)
- window.destroy()
- window = create_picker_window("Window Size", "300x200")
- tk.Label(window, text=f"Current: {segment_info['current_value']}").pack(pady=5)
- grid_frame = tk.Frame(window)
- grid_frame.pack(pady=5)
- for i, size in enumerate(presets):
- btn = tk.Button(grid_frame, text=size, width=10, command=lambda s=size: apply_size(s))
- btn.grid(row=i//3, column=i%3, padx=2, pady=2)
- add_standard_controls(window, apply_size)
- # Core Operations
- def clear_editor():
- for widget in scrollable_frame.winfo_children():
- widget.destroy()
- canvas.delete("bg_rect")
- def refresh_editor():
- clear_editor()
- for block_name in template_blocks:
- for line in template_blocks[block_name]['lines']:
- insert_line(line, block_name)
- tk.Frame(scrollable_frame, height=10, bg='black').pack(fill=tk.X, pady=0)
- draw_buffer()
- def update_segment(label, new_value):
- segment_info = label.segment_info
- old_segment = segment_info['segment']
- block_name = segment_info['block_name']
- if segment_info['type'] == 'text':
- new_segment = f"text='{new_value}'" if "text='" in old_segment else f"append('{new_value}')"
- elif segment_info['type'] == 'coord':
- new_segment = f"x={new_value}" if 'x=' in old_segment else f"y={new_value}"
- elif segment_info['type'] == 'color':
- new_segment = f"bg='{new_value}'" if 'bg=' in old_segment else f"fg='{new_value}'"
- elif segment_info['type'] in ('geometry', 'window'):
- new_segment = f"{segment_info['type']}({new_value}+0+0)"
- else: return
- update_template_block(block_name, old_segment, new_segment)
- label.config(text=new_segment)
- label.segment_info.update({
- 'segment': new_segment,
- 'current_value': new_value
- })
- def show_widget_options_menu(event):
- widget = event.widget
- parent = widget.master
- if not hasattr(parent, 'block_name'):
- return
- widget_type = parent.block_name.split()[0]
- current_lines = template_blocks[parent.block_name]['lines']
- widget_options = WIDGET_OPTIONS['widget_specific'].get(widget_type, [])
- if not widget_options:
- return
- window = create_topwindow(f"{widget_type} Options")
- listbox = tk.Listbox(window, selectmode=tk.MULTIPLE, height=30, width=30)
- scrollbar = tk.Scrollbar(window)
- scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
- listbox.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
- listbox.config(yscrollcommand=scrollbar.set)
- scrollbar.config(command=listbox.yview)
- for option in widget_options:
- listbox.insert(tk.END, option)
- if any(option in line for line in current_lines):
- listbox.selection_set(tk.END)
- tk.Button(window, text="Apply", command=lambda: [window.destroy(), update_editor_content()]).pack(side=tk.BOTTOM, fill=tk.X)
- def update_editor_content():
- clear_editor()
- for block_name in template_blocks:
- for line in template_blocks[block_name]['lines']:
- insert_line(line, block_name)
- tk.Frame(scrollable_frame, height=10, bg='black').pack(fill=tk.X, pady=0)
- draw_buffer()
- def toggle_feature(name):
- template_blocks[name]['enabled'] = not template_blocks[name]['enabled']
- for child in scrollable_frame.winfo_children():
- if hasattr(child, 'block_name') and child.block_name == name:
- label_bg, editable_bg = ('black', '#009900') if template_blocks[name]['enabled'] else ('#990000', 'red')
- child.configure(bg=label_bg)
- for sub in child.winfo_children():
- if hasattr(sub, 'segment_info'):
- sub.configure(bg=editable_bg)
- else:
- sub.configure(bg=label_bg)
- do_buffer()
- def run_script():
- try:
- full_script = ""
- for block_name in template_blocks:
- if template_blocks[block_name]['enabled']:
- full_script += template_blocks[block_name]['content'] + "\n\n"
- exec(full_script, {"tk": tk})
- except Exception as e:
- print(f"Error: {e}")
- def save_script():
- file = filedialog.asksaveasfilename(defaultextension=".py")
- if file:
- full_script = ""
- for block_name in template_blocks:
- if template_blocks[block_name]['enabled']:
- full_script += template_blocks[block_name]['content'] + "\n\n"
- with open(file, "w") as f:
- f.write(full_script)
- def draw_buffer():
- root.update_idletasks()
- def grab_and_display():
- x = canvas.winfo_rootx()
- y = canvas.winfo_rooty()
- w = canvas.winfo_width()
- h = canvas.winfo_height()
- x *= x_offset
- y *= y_offset
- w = x + w + w_offset
- h = y + h + h_offset
- img = ImageGrab.grab(bbox=(x, y, w, h))
- img = img.resize((canvas.winfo_width(), canvas.winfo_height()))
- canvas.tk_img = ImageTk.PhotoImage(img)
- root.after(250, grab_and_display)
- def do_buffer():
- overlay = tk.Label(canvas, image=canvas.tk_img)
- overlay.place(x=0, y=0, relwidth=1, relheight=1)
- draw_buffer()
- root.after(100, overlay.destroy)
- x_offset = 1.5
- y_offset = 1.51
- w_offset = 592
- h_offset = 302
- def on_editable_click(event):
- label = event.widget
- segment_info = label.segment_info
- if segment_info['type'] == 'color':
- show_color_picker(segment_info, label)
- elif segment_info['type'] in ('coord', 'geometry'):
- show_window_size_picker(segment_info, label)
- else:
- window = create_topwindow("Edit Value", "300x150")
- tk.Label(window, text=f"Edit {segment_info['type']}:").pack(pady=5)
- entry = tk.Entry(window, width=100)
- entry.insert(0, segment_info['current_value'])
- entry.pack(pady=5)
- entry.focus_set()
- tk.Button(window, text="Save", command=lambda: [update_segment(label, entry.get()), window.destroy()]).pack(pady=5)
- label.master.bind("<Button-1>", lambda e, name=segment_info['block_name']: toggle_feature(name))
- root = tk.Tk()
- root.title("GUI Script Builder")
- root.geometry("1200x640+0+0")
- script = '''
- # Geometry
- root = tk.Tk()
- root.geometry('1200x640')
- # Label
- tk.Label(root, text='text', bg='red', fg='white').place(x=10, y=10)
- # Entry
- tk.Entry(root, bg='red', fg='white').place(x=10, y=40)
- # Button
- tk.Button(root, text='text', bg='red', fg='white').place(x=10, y=70)
- # Clipboard
- def copy_text(data):
- root.clipboard_clear()
- root.clipboard_append(data)
- def paste_text():
- return root.clipboard_get()
- # Mouse
- def on_mouse_click(event):
- return event.x, event.y
- root.bind('<Button-1>', on_mouse_click)
- # Keyboard
- def on_key(event):
- return event.char
- root.bind('<Key>', on_key)
- '''
- template_blocks = {}
- for block in script.strip().split('# ')[1:]:
- if '\n' in block:
- header, content = block.split('\n', 1)
- header = header.strip()
- content = '# ' + header + '\n' + content
- else:
- header = block.strip()
- content = '# ' + header
- if header:
- template_blocks[header] = {
- 'content': content,
- 'enabled': True,
- 'lines': content.split('\n')
- }
- pattern = r"(?P<text>text='[^']*')|(?P<x>x=\d+)|(?P<y>y=\d+)|" \
- r"(?P<bg>bg='[^']*')|(?P<fg>fg='[^']*')|" \
- r"(?P<append>append\('[^']*'\))|" \
- r"(?P<geometry>geometry\('[^']*'\))|" \
- r"(?P<toplevel>[\w]+ = tk\.Toplevel\(.*?\))"
- presets = "600x400", "800x600", "1024x768", "1200x640", "1400x700", "1920x1080"
- colors = {
- "red": "#FF0000", "green": "#00FF00", "blue": "#0000FF",
- "yellow": "#FFFF00", "cyan": "#00FFFF", "magenta": "#FF00FF",
- "black": "#000000", "white": "#FFFFFF", "violet": "#8F00FF",
- "orange": "#FFA500", "purple": "#800080", "brown": "#A52A2A",
- "pink": "#FFC0CB", "lime": "#00FF00", "navy": "#000080",
- "teal": "#008080", "maroon": "#800000", "olive": "#808000",
- "light gray": "#F0F0ED", "dark gray": "#A9A9A9",
- "silver": "#C0C0C0", "dim gray": "#696969",
- "slate gray": "#708090", "light slate": "#778899"
- }
- type_map = {
- 'text': 'text',
- 'x': 'coord',
- 'y': 'coord',
- 'bg': 'color',
- 'fg': 'color',
- 'append': 'text',
- 'geometry': 'geometry',
- 'toplevel': 'window'
- }
- WIDGET_OPTIONS = {
- 'widget_specific': {
- 'Button': [
- 'command', 'default', 'height', 'overrelief', 'repeatdelay',
- 'repeatinterval', 'width'
- ],
- 'Canvas': [
- 'closeenough', 'confine', 'scrollregion', 'xscrollcommand',
- 'yscrollcommand', 'xscrollincrement', 'yscrollincrement'
- ],
- 'Checkbutton': [
- 'command', 'indicatoron', 'offvalue', 'onvalue', 'selectcolor',
- 'selectimage', 'variable'
- ],
- 'Entry': [
- 'exportselection', 'invalidcommand', 'justify', 'readonlybackground',
- 'show', 'validate', 'validatecommand', 'xscrollcommand'
- ],
- 'Frame': [
- 'container', 'height', 'width'
- ],
- 'Label': [
- 'height', 'wraplength'
- ],
- 'LabelFrame': [
- 'labelanchor', 'text'
- ],
- 'Listbox': [
- 'activestyle', 'exportselection', 'height', 'listvariable',
- 'selectmode', 'width', 'xscrollcommand', 'yscrollcommand'
- ],
- 'Menu': [
- 'postcommand', 'tearoff', 'tearoffcommand', 'title', 'type'
- ],
- 'Menubutton': [
- 'direction', 'indicatoron', 'state'
- ],
- 'Message': [
- 'aspect', 'justify'
- ],
- 'OptionMenu': [
- 'command', 'value'
- ],
- 'PanedWindow': [
- 'handlepad', 'handlesize', 'opaqueresize', 'orient', 'sashcursor',
- 'sashpad', 'sashrelief', 'sashwidth', 'showhandle'
- ],
- 'Radiobutton': [
- 'command', 'indicatoron', 'selectcolor', 'selectimage', 'value',
- 'variable'
- ],
- 'Scale': [
- 'bigincrement', 'command', 'digits', 'from_', 'label', 'length',
- 'resolution', 'showvalue', 'sliderlength', 'sliderrelief',
- 'tickinterval', 'to', 'variable'
- ],
- 'Scrollbar': [
- 'activerelief', 'command', 'elementborderwidth'
- ],
- 'Spinbox': [
- 'buttonbackground', 'buttoncursor', 'buttondownrelief', 'buttonuprelief',
- 'command', 'format', 'from_', 'increment', 'invalidcommand',
- 'values', 'wrap'
- ],
- 'Text': [
- 'autoseparators', 'blockcursor', 'endline', 'height',
- 'inactiveselectbackground', 'maxundo', 'spacing1', 'spacing2',
- 'spacing3', 'startline', 'tabs', 'tabstyle', 'undo', 'width',
- 'wrap', 'xscrollcommand', 'yscrollcommand'
- ],
- 'Toplevel': [
- 'container', 'menu', 'screen', 'use'
- ],
- 'Treeview': [
- 'columns', 'displaycolumns', 'height', 'selectmode', 'show'
- ],
- 'Progressbar': [
- 'orient', 'length', 'mode', 'maximum', 'value', 'variable'
- ],
- 'Separator': [
- 'orient'
- ],
- 'Sizegrip': [],
- 'Notebook': [
- 'height', 'padding', 'width'
- ],
- 'Combobox': [
- 'exportselection', 'justify', 'postcommand', 'state', 'textvariable',
- 'values', 'width'
- ]
- }
- }
- button_frame = tk.Frame(root)
- button_frame.pack(fill=tk.X, padx=5, pady=5)
- tk.Button(button_frame, text="Run Code", command=run_script).pack(side=tk.LEFT, padx=5)
- tk.Button(button_frame, text="Save Script", command=save_script).pack(side=tk.LEFT, padx=5)
- editor_frame = tk.Frame(root)
- editor_frame.pack(fill=tk.BOTH, expand=True)
- canvas, scrollable_frame = create_scrollable_frame(editor_frame)
- canvas.bind("<Button-3>", show_widget_options_menu)
- canvas.tk_img = None
- update_editor_content()
- root.mainloop()
Add Comment
Please, Sign In to add comment