【问题标题】:How to swap two objects' positions on a tkinter canvas如何在 tkinter 画布上交换两个对象的位置
【发布时间】:2019-04-18 00:18:09
【问题描述】:

我正在使用 tkinter 使用不同矩形的高度进行排序可视化程序。我能够随机化每个矩形的高度,但现在我被困在试图弄清楚如何相互切换两个矩形的位置。在开始尝试实现排序之前,我需要弄清楚如何做到这一点。

这是我目前所拥有的:

import tkinter as tk
import random

window = tk.Tk()
window.title('Sorting')
window.geometry('600x400')

xstart = 5
xend = 15
canvas = tk.Canvas(window, width='600', height='400')
canvas.pack()
barList = []
lengthList = []

for x in range(1,60):
    randomY = random.randint(1,390)
    bar = canvas.create_rectangle(xstart,randomY,xend,395, fill='red')
    barList.append(bar)
    xstart += 10
    xend +=10

for bar in barList:
    x = canvas.coords(bar)
    length = x[3]-x[1]
    lengthList.append(length)



window.mainloop()

【问题讨论】:

  • 你在哪里尝试交换矩形位置?
  • @alec_a 我没有,我试着弄乱了一些想法,但最后我想不出如何为此实现任何东西
  • effbot.org: Canvas - coords() 获取和设置位置。

标签: python python-3.x tkinter tkinter-canvas algorithm-animation


【解决方案1】:

这里有一个小例子可以帮助你入门:点击交换按钮时,它会交换位置 10 的矩形和位置 20 的矩形。

import tkinter as tk
import random


def swap_two_pos(pos_0, pos_1):
    """This does the graphical swapping of the rectangles on the canvas
    by moving one rectangle to the location of the other, and vice versa
    """    
    x_00, _, x_01, _ = canvas.coords(pos_0)
    x_10, _, x_11, _ = canvas.coords(pos_1)
    # moves each rectangle to the x position of the other; y remains unchanged
    canvas.move(pos_0, x_10-x_00, 0)
    canvas.move(pos_1, x_01-x_11, 0)


def random_sort():
    """Not a sort yet, but you have the bare bones operations
    so the swap is executed
    """
    pos_0 = barList[10]
    pos_1 = barList[20]
    swap_two_pos(pos_0, pos_1)
    # it is necessary to swap the values in the list too
    barList[10], barList[20] = barList[20], barList[10]


window = tk.Tk()
window.title('Sorting')
window.geometry('600x400')

# button to command the swap
tk.Button(window, text='swap', command=random_sort).pack()

xstart = 5
xend = 15
canvas = tk.Canvas(window, width='600', height='400')
canvas.pack()
barList = []
lengthList = []

for x in range(1,60):
    randomY = random.randint(1,390)
    bar = canvas.create_rectangle(xstart, randomY, xend, 395, fill='red')
    barList.append(bar)
    xstart += 10
    xend +=10

for bar in barList:
    x = canvas.coords(bar)
    length = x[3]-x[1]
    lengthList.append(length)

# hardcoded colors so the swap is more visual
canvas.itemconfig(barList[10], fill='blue')
canvas.itemconfig(barList[20], fill='yellow')

window.mainloop()

【讨论】:

  • 我建议使用比abcd 更有用的变量名称。使用 x1y1x2y2(或类似的东西)使代码更加不言自明。
  • 是的,谢谢@Bryan 的建议,我本来打算改变它,但不知何故忘记了。
  • 非常感谢,这正是我需要了解的
猜你喜欢
  • 2011-10-19
  • 2014-09-02
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多