Sujet : POTD: Linux-Windows TUI
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 08. Sep 2024, 20:41:39
Autres entêtes
Organisation : Stefan Ram
Message-ID : <windows-20240908202958@ram.dialup.fu-berlin.de>
Whipped up this gnarly POTD ("program of the day") in a hot minute.
My AI homie threw me a bone.
It wipes the slate clean and spits out a rando number when you smash
the space bar. This bad boy only needs the standard library.
It's golden on Linux and Windows.
On Linux, where there's curses in the mix, we roll with that.
On Windows, we kick it with tkinter instead. Use this as your
secret sauce for portable TUI software!
If there are still any bugs, that's on me. Don't throw shade at
my AI wingman!
import random
import sys
import os
# Determine the operating system
is_windows = os.name == 'nt'
if is_windows:
import tkinter as tk
else:
import curses
class RandomNumberGenerator:
def __init__(self):
self.random_range = (1, 1000)
def generate_number(self):
return random.randint(*self.random_range)
class LinuxApp(RandomNumberGenerator):
def run(self):
def main(stdscr):
while True:
key = stdscr.getch()
if key == ord(' '):
stdscr.clear()
stdscr.addstr(str(self.generate_number()))
stdscr.refresh()
elif key == ord('q'):
break
curses.wrapper(main)
class WindowsApp(RandomNumberGenerator):
def run(self):
root = tk.Tk()
root.title("Random Number Generator")
text_widget = tk.Text(root, height=5, width=30)
text_widget.pack(padx=10, pady=10)
text_widget.insert(tk.END, "Press SPACE to generate a random number")
def generate_number_gui(event):
text_widget.delete(1.0, tk.END)
text_widget.insert(tk.END, str(self.generate_number()))
root.bind('<space>', generate_number_gui)
root.mainloop()
def main():
app = WindowsApp() if is_windows else LinuxApp()
app.run()
if __name__ == "__main__":
main()