maxutil
maxutil

Reputation: 195

Python - Can you help me make a class from a piece of code I'm repeating?

Below I am reusing a piece of code when I set the instruct1 and instruct2 variables. I tried a couple of things yesterday to make a class but was unable to do it properly. Would anyone be willing to help? Thanks in advance.

import tkinter as tk
from tkinter import ttk

HEIGHT = 700
WIDTH = 1100

root = tk.Tk()

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

frame = tk.Frame(root, bg='#08295e')
frame.place(relx=0.01, rely=0.01, relwidth=0.98, relheight=0.98)

prog_title = tk.Label(frame, text='test program')
prog_title.config(width=30, font=('Eras Medium ITC', 30), bg='#08295e', fg='white', bd=7)
prog_title.pack()

instruct1 = tk.Label(frame, text='Step1: Do step 1', anchor='nw')
instruct1.config(width=30, font=('Microsoft JhengHei Light', 15), bg='#08295e', fg='white')
instruct1.place(relx=0.05, rely=0.1)

instruct2 = tk.Label(frame, text='Step2: Do step 2', anchor='nw')
instruct2.config(width=30, font=('Microsoft JhengHei Light', 15), bg='#08295e', fg='white')
instruct2.place(relx=0.05, rely=0.2)

s = ttk.Style()
s.configure('my.TButton', font=('Microsoft JhengHei Light', 12))

button = ttk.Button(root, text='Create Stuff', style='my.TButton')
button.place(relx=0.5, rely=0.3, relwidth=0.17, relheight=0.05)

root.mainloop()

Upvotes: 0

Views: 56

Answers (1)

Dschoni
Dschoni

Reputation: 3862

Just look, which values are constant between this lines and wrap them inside a function and define the others to be parameters.

def make_label(my_text, my_offset):
      temp = tk.Label(frame, text=my_text, anchor='nw')
      temp.config(width=30, font=('Microsoft JhengHei Light', 15), bg='#08295e', fg='white')
      temp.place(relx=0.05, rely=my_offset)
      return temp

instruct1 = make_label('Step1: Do step 1', 0.1)       
instruct2 = make_label('Step2: Do step 2', 0.2)

Upvotes: 1

Related Questions