为什么在此python脚本中什么都没有移动?

如何解决为什么在此python脚本中什么都没有移动?

因此,我从python书籍中复制了此代码,该代码本来就像一个鸡蛋捕手游戏,但是,如果您运行该代码,则可以看到,tkinter会创建所有内容,但是该游戏将进行设置本身不会启动。有人知道如何开始吗?我尝试按下按钮并使整个功能正常运行,但是它们都无法正常工作。这是我的下面的代码...

from itertools import cycle
from random import randrange
from tkinter import Canvas,Tk,messagebox,font

canvas_width = 800
canvas_height = 400

root = Tk()
c = Canvas(root,width=canvas_width,height=canvas_height,background='deep sky blue')
c.create_rectangle(-5,canvas_height - 100,canvas_width + 5,canvas_height + 5,\
                    fill='sea green',width=0)
c.create_oval(-80,-80,120,fill='orange',width=0)
c.pack()
color_cycle = cycle(['light blue','light green','light pink','light yellow','light cyan'])
egg_width = 45
egg_height = 55
egg_score = 10
egg_speed = 500
egg_interval = 4000
difficulty_factor = 0.95
catcher_color = 'blue'
catcher_width = 100
catcher_height = 100
catcher_start_x = canvas_width / 2 - catcher_width / 2
catcher_start_y = canvas_height - catcher_height - 20
catcher_start_x2 = catcher_start_x + catcher_width
catcher_start_y2 = catcher_start_y + catcher_height

catcher = c.create_arc(catcher_start_x,catcher_start_y,\
 catcher_start_x2,catcher_start_y2,start=200,extent=140,\
 style='arc',outline=catcher_color,width=3)
game_font = font.nametofont('TkFixedFont')
game_font.config(size=18)
score = 0
score_text = c.create_text(10,10,anchor='nw',font=game_font,fill='darkblue',\
 text='Score: ' + str(score))
lives_remaining = 3
lives_text = c.create_text(canvas_width - 10,anchor='ne',\
 text='Lives: ' + str(lives_remaining))
eggs = []
def create_egg():
 x = randrange(10,740)
 y = 40
 new_egg = c.create_oval(x,y,x + egg_width,y + egg_height,fill=next(color_cycle),width=0)
 eggs.append(new_egg)
 root.after(egg_interval,create_egg)
def move_eggs():
 for egg in eggs:
     (egg_x,egg_y,egg_x2,egg_y2) = c.coords(egg)
     c.move(egg,10)
     if egg_y2 > canvas_height:
         egg_dropped(egg)
         root.after(egg_speed,move_eggs)
def egg_dropped(egg):
 eggs.remove(egg)
 c.delete(egg)
 lose_a_life()
 if lives_remaining == 0:
     messagebox.showinfo('Game Over!','Final Score: ' + str(score))
     root.destroy()
def lose_a_life():
 global lives_remaining
 lives_remaining -= 1
 c.itemconfigure(lives_text,text='Lives: ' + str(lives_remaining))
def check_catch():
 (catcher_x,catcher_y,catcher_x2,catcher_y2) = c.coords(catcher)
 for egg in eggs:
     (egg_x,egg_y2) = c.coords(egg)
     if catcher_x < egg_x and egg_x2 < catcher_x2 and catcher_y2 - egg_y2 < 40:
         eggs.remove(egg)
         c.delete(egg)
         increase_score(egg_score)
         root.after(100,check_catch)
def increase_score(points):
 global score,egg_speed,egg_interval
 score += points
 egg_speed = int(egg_speed * difficulty_factor)
 egg_interval = int(egg_interval * difficulty_factor)
 c.itemconfigure(score_text,text='Score: ' + str(score))
def move_left(event):
 (x1,y1,x2,y2) = c.coords(catcher)
 if x1 > 0:
     c.move(catcher,-20,0)
def move_right(event):
 (x1,y2) = c.coords(catcher)
 if x2 < canvas_width:
     c.move(catcher,20,0)
     c.bind('<Left>',move_left)
     c.bind('<Right>',move_right)
     c.focus_set()
     root.after(1000,create_egg)
     root.after(1000,move_eggs)
     root.after(1000,check_catch)
     root.mainloop()

解决方法

我看到了很多函数,但没有调用它们,尤其是运行Tkinter主循环的函数。

鉴于您期望move_left()move_right()函数之间的相似性,几乎可以肯定的是,该函数的最后一行不应 缩进到它们的位置

使用您的 current 代码,仅在调用move_right()时执行执行绑定和计时器回调设置的行。并非如此,因为将调用的键绑定仅在调用时设置(这不是因为...

WARNING W-42: thought process terminated due to likely stack overflow in wet-ware:-)

换句话说,您的代码应类似于:

def move_left(event):
    (x1,y1,x2,y2) = c.coords(catcher)
    if x1 > 0:
        c.move(catcher,-20,0)

def move_right(event):
    (x1,y2) = c.coords(catcher)
    if x2 < canvas_width:
        c.move(catcher,20,0)

# Run this at top level,NOT as part of move_right().

c.bind('<Left>',move_left)
c.bind('<Right>',move_right)
c.focus_set()
root.after(1000,create_egg)
root.after(1000,move_eggs)
root.after(1000,check_catch)
root.mainloop()

顺便说一句,这可能只是粘贴代码的方式,但是在编写代码时,您应该尝试遵循PEP8样式指南,特别是缩进四个空格的指南。它们通常使您的代码更易于阅读和/或分析。


而且,正如您所知道的那样,这些move_xxx()函数实际上将使您的捕捉器脱离屏幕边缘(我认为最多20像素)。如果这不是您想要的,则可能需要进行一些更改:

move_sz = 20

def move_left(event):
    (x1,y2) = c.coords(catcher)
    c.move(catcher,-min(move_sz,x1),min(move_sz,canvas_width - x2 - 1),0)

我还没有测试过(特别是可能超出一个像素-我会把它留给你),但是这个想法只是为了限制您的移动量,以免将捕捉器发送到画布边界之外

您会看到我还用一个更合适的变量替换了魔法常数20-这样,如果您要调整移动速度,只需要将其更改为一个位置即可。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 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时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;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,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;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[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 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 -&gt; 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(&quot;/hires&quot;) 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&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-