Simple way to display text on screen in Python?

后端 未结 2 1547
再見小時候
再見小時候 2020-12-16 08:55

I\'ve been googling and looking through StackOverflow but no luck...

What I would like is to display text to the screen (not console) for an art project I am develop

2条回答
  •  执笔经年
    2020-12-16 09:10

    You can easily do this sort of thing with Tkinter, which is included in most modern Python installations. Eg,

    import tkinter as tk
    from random import seed, choice
    from string import ascii_letters
    
    seed(42)
    
    colors = ('red', 'yellow', 'green', 'cyan', 'blue', 'magenta')
    def do_stuff():
        s = ''.join([choice(ascii_letters) for i in range(10)])
        color = choice(colors)
        l.config(text=s, fg=color)
        root.after(100, do_stuff)
    
    root = tk.Tk()
    root.wm_overrideredirect(True)
    root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
    root.bind("", lambda evt: root.destroy())
    
    l = tk.Label(text='', font=("Helvetica", 60))
    l.pack(expand=True)
    
    do_stuff()
    root.mainloop()
    

    Click with the left mouse button to exit.

    This is just a proof of concept. To control color &/or font on a letter-by-letter basis you'll need to do something a little more complicated. You could use a row of Label widgets (one for each letter), or you could use a Text widget.


    However, if you try this on a Mac, the window may not receive focus, as mentioned here. The answers here show an alternative way to get a fullscreen window, but I suspect it could suffer from the same defect.

    root.attributes("-fullscreen", True)
    

    One advantage of this approach is that it doesn't require the root.geometry call.

提交回复
热议问题