我试图为基于文本的应用程序创建一个tkinter输出窗口

2024-05-23 22:48:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,它持续接收文本并输出文本(这是一个基于文本的游戏)

我想通过tkinter图形用户界面来运行它,而不是控制台

Python : Converting CLI to GUI

这个问题完美地回答了如何将“print”转换成GUI插件。

问题是,我的游戏显然运行了大量的循环,这会使“app.mainloop()”变得一团糟,因为它要么从不运行(然后图形用户界面也不会出现),要么你先运行它,它不会让其他任何东西运行。

我想我可以尝试和交错这些循环不知何故,但这似乎非常黑客。我也可以尝试修改整个代码库,使其在app.mainloop()中运行,但我真正需要的是多个线程。问题是,我不知道该怎么做。

还有一些其他问题,但它们要么不起作用,要么没有多大意义: Tkinter with multiple threads

Run process with realtime output to a Tkinter GUI

谢谢。

编辑:极其简化的代码:

def moveNorth():
    print('You have moved north')

def interpreter(command):
    if command == 'go north':
         moveNorth()
    else:
         print('invalid command')

def listener():
     playerchoice = sys.stdin.readline().strip()
     return playerchoice

if __name__ == '__main__':
    print('Welcome')
    while playing:
        interpreter(listener())

Tags: to代码文本app游戏tkinterdefwith