← Back to Python Course | Chapter 14: Advanced Python & Tools | Lesson 12 of 15

Python tkinter परिचय

Tkinter आपको अपनी screen पर buttons और text वाली windows बनाने देता है, बिल्कुल अपनी खुद की एक छोटी app बनाने जैसा। Window खुली रहती है और आपके कुछ click करने का इंतज़ार करती है।
Syntax
python
import tkinter as tk

root = tk.Tk()
root.title("title")
# add widgets here
root.mainloop()

Tkinter क्या है?

Tkinter, Python की standard-library GUI toolkit है, जो अलग से install करने की ज़रूरत नहीं होती बल्कि खुद interpreter के साथ bundled आती है।

Turtle graphics की तरह, इसे चलाने के लिए भी एक असली graphical display चाहिए, हालाँकि Pyodide जैसे browser-based environments Tkinter windows को सीधे page में render कर सकते हैं।

उदाहरण: What is Tkinter?

python
import tkinter
print(tkinter.TkVersion)

एक Window बनाना

हर Tkinter application Tk() के ज़रिए एक root window instance बनाकर शुरू होता है, जो main application window को represent करता है जिसके अंदर बाकी सभी widgets रखे जाते हैं।

उदाहरण: Creating a Window

python
import tkinter
root = tkinter.Tk()  # main application window everything else is placed inside
print(type(root))

Event Loop

नई बनाई गई Tkinter window तुरंत बंद हो जाती है जब तक आप mainloop() call न करें, जो event loop शुरू करता है और window बंद होने तक उसे खुला रखता है, दोबारा draw करता है, और clicks व keypresses जैसी user interactions के लिए लगातार सुनता रहता है।

उदाहरण: The Event Loop

python
import tkinter
root = tkinter.Tk()
root.after(100, root.destroy)  # auto-close so this demo doesn't hang
root.mainloop()
print("Event loop ended")

Window Titles जोड़ना

title('My App'), window की title bar में दिखने वाला text set करता है, जो users को application पहचानने के लिए एक स्पष्ट label देता है -- यह एक छोटी सी detail है, पर इसे भूलना आसान है और window अजीब तरह से बिना label के रह जाती है।

उदाहरण: Adding Window Titles

python
import tkinter
root = tkinter.Tk()
root.title("My App")  # sets the text shown in the title bar
print(root.title())

Window Dimensions सेट करना

geometry(widthxheight) एक specific string format (जैसे 400x300) इस्तेमाल करके window के initial pixel dimensions सेट करता है, जिससे आप default size पर निर्भर रहने की बजाय यह control कर सकते हैं कि application window पहली बार खुलने पर कितनी बड़ी दिखे।

उदाहरण: Setting Window Dimensions

python
import tkinter
root = tkinter.Tk()
root.geometry("400x300")  # sets the initial pixel dimensions
print(root.geometry())
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.