我想在我的Tinter画布上制作一个网格/粒子网格。然后我想使用canvas.move函数从文本文件中读取坐标来移动这些粒子。我试着把格子弄成一个循环。
from Tkinter import *
import random
import time
import csv
tk = Tk()
N = 100
T = 500
canvas = Canvas(tk, width=100, height=100)
tk.title("Test")
canvas.pack()
n = 5
t = 10
step1 = []
step2 = []
textFile1 = open('/Users/francislempp/Desktop/major project/C++ programs/Molecular Dynamics 2D/Molecular_Dynamics_2D- gupnvjunowwmjcfiyoursdhzytow/Build/Products/Debug/motionX', 'r')
lines = textFile1.readlines()
for line in lines:
step1.append(line.split(" "))
textFile2 = open('/Users/francislempp/Desktop/major project/C++ programs/Molecular Dynamics 2D/Molecular_Dynamics_2D-gupnvjunowwmjcfiyoursdhzytow/Build/Products/Debug/motionY', 'r')
lines = textFile2.readlines()
for line in lines:
step2.append(line.split(" "))
class Ball:
def __init__(self, color, size, x, y):
self.shape = canvas.create_oval(10,10,size,size, fill = color)
self.x = x
self.y = y
def move(self):
canvas.move(self.shape, self.x, self.y)
pos = canvas.coords(self.shape)
if pos[3] >= 100 or pos[1] <= 0:
self.y = -self.y
if pos[2] > 100 or pos[0] <= 0:
self.x = -self.x
def delete(self):
canvas.delete(self.shape)
balls = []
for i in range(99):
for j in range(99):
xcoord = i*(100/10) + 4
ycoord = j*(100/10) + 4
canvas.create_oval(xcoord,ycoord,2,2, fill = "red")
tk.update()
tk.mainloop()
当我运行我的代码时,它会使椭圆沿着屏幕向下移动并相互重叠。我想for循环在画布内放置100个粒子,间距相等。
答案 0 :(得分:0)
您必须使用(x, y, x+1, y+1)
甚至(x, y, x, y)
来创建相同大小的小点。
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=100, height=100)
canvas.pack()
for i in range(10):
x = i*10 + 4
for j in range(10):
y = j*10 + 4
canvas.create_oval(x, y, x, y, fill="red")
#canvas.create_oval((x, y, x, y), fill="red") # or with `()`
root.mainloop()
或使用range()
for x in range(4, 100, 10):
for y in range(4, 100, 10):
canvas.create_oval((x, y, x, y), fill="red")
编辑:以相同方向移动(随机)所有点
import tkinter as tk
import random
# --- functions ---
def move():
x = random.randint(-1, 1)
y = random.randint(-1, 1)
for point_id in points:
canvas.move(point_id, x, y)
root.after(100, move)
# --- main ---
points = []
root = tk.Tk()
canvas = tk.Canvas(root, width=100, height=100)
canvas.pack()
for i in range(10):
x = i*10 + 4
for j in range(10):
y = j*10 + 4
point_id = canvas.create_oval(x, y, x, y, fill="red")
points.append(point_id)
#canvas.create_oval((x, y, x, y), fill="red") # or with `()`
move()
root.mainloop()
或者向不同方向移动每个像素
def move():
for point_id in points:
x = random.randint(-1, 1)
y = random.randint(-1, 1)
canvas.move(point_id, x, y)
root.after(100, move)