Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
How to place a button at any position in Tkinter?
Next article icon

Prerequisite:Tkinter

Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications.

In this article, we will learn how to make an on/off switch using Tkinter.

Approach:

  • Make a global variable named asis_on; the default value is True, which indicates the switch is ON.
  • Make twoImageObjects; one object has"on image" and another one has"off image".
  • Create a button that has"on image" as default; set the border width to be zero.
  • Make a function that will change the button image, using theconfig() method.
  • The function will check, whether theis_on value isTrueorFalse

Image link:

Below is the Implementation:

Python3
# Import Modulefromtkinterimport*# Create Objectroot=Tk()# Add Titleroot.title('On/Off Switch!')# Add Geometryroot.geometry("500x300")# Keep track of the button state on/off#global is_onis_on=True# Create Labelmy_label=Label(root,text="The Switch Is On!",fg="green",font=("Helvetica",32))my_label.pack(pady=20)# Define our switch functiondefswitch():globalis_on# Determine is on or offifis_on:on_button.config(image=off)my_label.config(text="The Switch is Off",fg="grey")is_on=Falseelse:on_button.config(image=on)my_label.config(text="The Switch is On",fg="green")is_on=True# Define Our Imageson=PhotoImage(file="on.png")off=PhotoImage(file="off.png")# Create A Buttonon_button=Button(root,image=on,bd=0,command=switch)on_button.pack(pady=50)# Execute Tkinterroot.mainloop()

Output:


Improve

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp