Home > OS >  How can i open a text in a window?
How can i open a text in a window?

Time:01-02

so i was making a Ping pong game, and i forgot something very important, adding text! so i searched up a tutorial, and i found NONE, looked at some of posts, NONE, so i decided, to ask the comunity once again, (because i am new at python) anyways, i need to put text inside of this code.

import tkinter as tk

class Main:
    def __init__ (self,root):
        self.root = root
        self.root.title("Ping Pong in Python")
        self.root.geometry("2000x2000")

        self.canvas = tk.Canvas(root, width=400, height=400, background="red")
        self.canvas.pack(fill="both", expand=True)

if __name__ == '__main__':
    root = tk.Tk()
    obj = Main(root)
    root.mainloop()

i tried searching up at youtube, found NONE, which i expected, because nowadays people only explain what they think is useful at youtube, so i searched up at stack overflow (this website) which i found one, but was closed, and didn't even work like last time! so i expected this again, so i decided to ask the comunity once again.

CodePudding user response:

Google is your best friend. "Tkinter Text" lead to https://www.tutorialspoint.com/python/tk_text.htm

CodePudding user response:

import tkinter as tk

class Main:
    def __init__ (self,root):
        self.root = root
        self.root.title("Ping Pong in Python")
        self.root.geometry("2000x2000")

        self.canvas = tk.Canvas(root, width=400, height=400, background="red")
        self.canvas.pack(fill="both", expand=True)

        # Add text
        self.text = tk.Label(self.root, text="Ping Pong text")
        self.text.pack()
        self.text.place(relx=0.5, rely=0.1, anchor=tk.N)

if __name__ == '__main__':
    root = tk.Tk()
    obj = Main(root)
    root.mainloop()

The "relx" parameter specifies the horizontal position of the text (0 being the left edge and 1 being the right edge). The "rely" parameter specifies the vertical position of the text (0 being the top edge and 1 being the bottom edge). The "anchor" parameter specifies which point of the text widget should be placed at the specified position. For example, tk.N specifies that the top of the text widget should be placed at the top of the window.

  • Related