将Python中的stdout重定向到PyGame

如何解决将Python中的stdout重定向到PyGame

我这里有一个非常奇怪的用例,我正在尝试为我的学生整理一些简单的程序,以帮助他们学习python。为了使其正常工作,我在TKinter框架中嵌入了一个PyGame窗口,并且需要重定向stdout来更改PyGame窗口中的某些内容。我可以进行重定向,如果我将其重定向到文件,则可以正常工作,但如果尝试更改文本,则无法正常工作。我将一个字符串硬编码到PyGame文本更改代码中,并且可以使用,但是由于某种原因,它不能用于重定向的文本。

重定向类:

class PrintTest:
    def __init__(self,file,game):
        self.f = file
        self.game = game
    
    def write(self,t):
        f.write(t)

        self.game.text = game.font.render(t,True,self.game.text_colors[1],self.game.text_colors[2])
        self.game.textRect = self.game.text.get_rect()

        self.game.textRect.center = (300,300)

    def flush(self):
        pass

游戏类:

class Game:
    def __init__(self,root):
        self.root = root
        embed = tk.Frame(root,width=600,height=600)
        embed.pack(side=tk.LEFT)

        os.environ['SDL_WINDOWID'] = str(embed.winfo_id())
        if platform.system == "Windows":
            os.environ['SDL_VIDEODRIVER'] = 'windib'

        self.text_colors = [(255,255,255),(0,0),128)]

        # initialize a pygame display
        pygame.init()
        self.screen = pygame.display.set_mode((600,600))
        self.screen.fill(pygame.Color('red'))
        self.clock = pygame.time.Clock()

        self.font = pygame.font.Font('freesansbold.ttf',32)
        self.text = self.font.render('Hello,world!',self.text_colors[1],self.text_colors[2])
        self.textRect = self.text.get_rect()

        self.textRect.center = (300,300)

        # TK Creation
        helv = font.Font(family='Helvetica',size=18,weight='bold')
        self.button = tk.Button(root,text="Change text",font=helv,command=self.change_text).pack()

        self.user_input = tk.StringVar()
        self.textbox = ttk.Entry(root,width=15,textvariable=self.user_input)
        self.textbox.pack()
        # ---------------------------------------------------------------

    def change_text(self):
        print(self.user_input.get())

    def run(self):
        # Pygame loop
        running = True
        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False

            self.screen.fill(pygame.Color('red'))    

            self.screen.blit(self.text,self.textRect)

            pygame.display.update()

            try:
                self.root.update()
            except tk.TclError:
                running = False   
        pygame.quit()

我这样设置标准输出:

try:
    root = tk.Tk()
    root.geometry('1000x600')

    game = Game(root)

    f = open('text.txt','w')
    sl = PrintTest(f,game)
    sys.stdout = sl

    game.run()
except Exception:
    traceback.print_exc()
    pygame.quit()

按原样运行时,如果在框中键入hello,则hello会打印到文件中,但pygame框中会放入一个空字符。我对PyGame并不十分了解,无法确定这到底是问题还是重定向问题。任何帮助将不胜感激!

(如果您想知道这里的用例,我将让他们“完成”一些程序以使PyGame发生某些事情。因此,如果他们在给定的类型中键入print('Hello Friend!')字段,它将重定向为在PyGame框中与某人对话。从长远来看,它可能无法正常工作,但我必须克服这个问题才能真正找出答案)

编辑:

所以问题在于,由于某种原因,当我单击按钮时,两次调用写函数,它是在键入的字符串上调用print,然后在空字符串上再次调用print。仍然不确定如何解决它,但至少我发现了问题

解决方法

好的,所以我找到了问题。

打印似乎将两件事发送到stdout,即要打印的字符串和结尾字符。因此它覆盖了我想用换行符打印的字符串。我更改了PrintTest类以适应此情况:

%dw 2.0
var in1=[
{
  "CustomerID": "123","Name": "Maria","Phone": "030-0074321"
},{
  "CustomerID": "56654","Name": "sdf","Phone": "030-6877452"
}
]
var in2=[
  {
    "OrderID": "10643","CustomerID": "123","Price": "200"
  },{
    "OrderID": "10692","Price": "566"
  },{
    "OrderID": "10702","CustomerID": "56654","Price": "546"
  }
]
fun getCommonKey(key1,key2) = key1 -- (key1 -- key2)
var commonKey = getCommonKey(flatten(in1 map keysOf($)) distinctBy $,flatten(in2 map keysOf($)) distinctBy $)
fun getPrimaryKey(v)=(commonKey map (v1,i1) -> {
          name:v1,value: v[(v1)]
  }.value) joinBy "-"
output application/json
---
in1 map (v,i) ->{
  (v),(using (pkId=getPrimaryKey(v),in2WithForeignKey = in2 map (v2,i2) ->
      {
        foreignKey: (commonKey map (v1,i1) -> {
            name:v1,value: v2[(v1)] default ""
        }.value )  joinBy "-",(v2)
      }
      ){
        (using (details = ((in2WithForeignKey[?($.foreignKey == pkId)] default [])
            map (($ -- (commonKey)) - "foreignKey" ))) {
            (Details: details) if (!isEmpty(details))
      })
  })
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-