如何用python的Tkinter实现一个正方形一直移动
时间: 2024-05-05 12:19:03 浏览: 159
在屏幕上?
可以使用Tkinter的canvas和animation功能来实现正方形的移动。具体如下:
1.导入Tkinter和time模块
```python
import tkinter as tk
import time
```
2.创建窗口和画布
```python
win = tk.Tk()
win.title("移动正方形")
canvas = tk.Canvas(win, width=400, height=400)
canvas.pack()
```
3.在画布上创建正方形
```python
square = canvas.create_rectangle(50, 50, 100, 100, fill="red")
```
4.定义正方形的移动函数
```python
def move_square(dx, dy):
canvas.move(square, dx, dy)
win.update()
time.sleep(0.01)
move_square(dx, dy)
```
5.调用移动函数并启动窗口的循环
```python
move_square(1, 1)
win.mainloop()
```
完整代码如下:
```python
import tkinter as tk
import time
win = tk.Tk()
win.title("移动正方形")
canvas = tk.Canvas(win, width=400, height=400)
canvas.pack()
square = canvas.create_rectangle(50, 50, 100, 100, fill="red")
def move_square(dx, dy):
canvas.move(square, dx, dy)
win.update()
time.sleep(0.01)
move_square(dx, dy)
move_square(1, 1)
win.mainloop()
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)