I want to shorten the length of the Python cord

Asked 2 years ago, Updated 2 years ago, 14 views

button1  = Button(window,text="    ",bg="skyblue",command=process1)
button2  = Button(window,text="    ",bg="skyblue",command=process2)
button3  = Button(window,text="    ",bg="skyblue",command=process3)
button4  = Button(window,text="    ",bg="skyblue",command=process4)
button5  = Button(window,text="    ",bg="skyblue",command=process5)
button6  = Button(window,text="    ",bg="skyblue",command=process6)
button7  = Button(window,text="    ",bg="skyblue",command=process7)
button8  = Button(window,text="    ",bg="skyblue",command=process8)
button9  = Button(window,text="    ",bg="skyblue",command=process9)
button10 = Button(window,text="    ",bg="skyblue",command=process10)

Do I have to write a repeat sentence? How can I reduce it?

python

2022-09-21 21:32

2 Answers

Yes. Write a repeat sentence.


2022-09-21 21:32

There are many ways.

How to use containers such as lists

eventPtrs = (process1, process2, process3)
buttonContainer = []
for eventPtr in eventPtrs:
    buttonContainer.append(Button(window,text="    ",bg="skyblue",command=eventPtr)) 

buttonContainer[0] #First button 

How to use reflection

import sys
mod = sys.modules[__name__]
eventPtrs = (process1, process2, process3)
for k, eventPtr in enumerate(eventPtrs ):
    setattr(mod, 'button{}'.format(k), Button(window,text="    ",bg="skyblue",command=eventPtr))

Button0 # First button


2022-09-21 21:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.