You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter程序无报错却显示空白窗口问题求助

问题:Tkinter窗口显示空白,无报错

程序运行后仅显示空白窗口,无任何报错,代码如下:

from tkinter import *

root=Tk()
root.geometry("400x400")

width,height= 400, 400

canvas = Canvas (root, width=width,height= height, bg="black")

shape=canvas.create_oval (width/2,height/2,width/2+10,height/2+10, fill="yellow")


def Left(event):
    x= -10
    y=-0
    canvas.move(shape,x,y)

def Right(event):
    x=10
    y=0
    canvas.move(shape,x,y)

def Up(event):
    x=0
    y=-10
    canvas.move(shape,x,y)

def Down(event):
    x=0
    y=10
    canvas.move(shape,x,y)

root.bind("<Left>",Left)
root.bind("<Right>",Right)
root.bind("<Up>",Up)
root.bind("<Down>",Down)
root.mainloop()
解决方法

问题核心是Canvas组件未被添加到窗口布局中。Tkinter创建组件后,必须通过pack()、grid()或place()方法将其纳入窗口显示布局,否则组件不会被渲染。

在创建Canvas的代码后添加一行布局代码即可:

canvas.pack()  # 也可使用canvas.grid()或canvas.place(x=0,y=0)

修改后的完整代码:

from tkinter import *

root=Tk()
root.geometry("400x400")

width,height= 400, 400

canvas = Canvas (root, width=width,height= height, bg="black")
canvas.pack()  # 添加布局代码

shape=canvas.create_oval (width/2,height/2,width/2+10,height/2+10, fill="yellow")


def Left(event):
    x= -10
    y=0
    canvas.move(shape,x,y)

def Right(event):
    x=10
    y=0
    canvas.move(shape,x,y)

def Up(event):
    x=0
    y=-10
    canvas.move(shape,x,y)

def Down(event):
    x=0
    y=10
    canvas.move(shape,x,y)

root.bind("<Left>",Left)
root.bind("<Right>",Right)
root.bind("<Up>",Up)
root.bind("<Down>",Down)
root.mainloop()

另外可将代码里的y=-0改为y=0,不影响功能但更规范。

内容的提问来源于stack exchange,提问作者nev nev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 15:39:21