[파이썬] tkinter 텍스트 박스(`Text`) 위젯

The tkinter library in Python provides a Text widget that is used for displaying and editing multiple lines of text. It is a versatile widget that allows users to input and manipulate text within an application.

Creating a Text widget

To create a Text widget in tkinter, you can use the following code:

import tkinter as tk

root = tk.Tk()

text_widget = tk.Text(root, height=10, width=30)
text_widget.pack()

root.mainloop()

In the above code, we import the tkinter module and create an instance of the Tk class to create the main window. We then create a Text widget using the Text() constructor and specify the desired height and width. Finally, we call the pack() method to add the widget to the window and start the event loop using the mainloop() method.

Adding and retrieving text

You can add text to the Text widget using its insert() method. To retrieve the text entered by the user, you can use the get() method. Here’s an example:

import tkinter as tk

def get_text():
    text = text_widget.get("1.0", tk.END)
    print(text)

root = tk.Tk()

text_widget = tk.Text(root, height=10, width=30)
text_widget.pack()

button = tk.Button(root, text="Get Text", command=get_text)
button.pack()

root.mainloop()

In the above code, we define a function get_text() that retrieves the text from the Text widget using the get() method. We pass "1.0" as the starting position and tk.END as the ending position to get all the text in the widget. When the user clicks the “Get Text” button, the get_text() function is called and the text is printed to the console.

Modifying text properties

You can modify various properties of the text within the Text widget, such as font style, size, and weight. Here’s an example of how to change the font size and weight of the text:

import tkinter as tk
from tkinter import font

root = tk.Tk()

text_widget = tk.Text(root, height=10, width=30)
text_widget.pack()

custom_font = font.Font(size=12, weight="bold")
text_widget.configure(font=custom_font)

root.mainloop()

In the above code, we import the font module from tkinter and create a custom font using the Font() constructor. We specify the desired font size and weight and assign the custom font to the font property of the Text widget using the configure() method.

Conclusion

The Text widget in tkinter provides an easy way to incorporate text input and display functionality in your Python applications. By understanding the basic usage and available methods, you can create powerful text-based features within your tkinter GUIs.