排序的GUI:如何在排序过程中为某些数字上色?

2 投票
3 回答
789 浏览
提问于 2025-04-17 12:38

我的冒泡排序代码在图形界面中的样子是这样的:

def bubble(self):
    def bubble_sort ( array ) :
        swap_test = False
        for i in range ( 0, len ( array ) - 1 ):
         for j in range ( 0, len ( array ) - i - 1 ):
          if array[j] > array[j + 1] :
           array[j], array[j + 1] = array[j + 1], array[j]#elegentan way of swap

           swap_test = True
           break
           #if swap_test == False:
        #else:
        #self.create_label()

   #print('bubble to be implemented')
    bubble_sort(self.nums)
    return self.nums

我想给那些在一步中被交换的元素上色,比如说 array[j] 和 array[j+1] 被交换的时候。

用于排序按钮和将结果存储到标签中的函数是:

def sortit(self):
    function = self.function[self.v.get()]
    result = function()
    num = ''.join('%4i' % num for num in result)
    self.label3 = Label(self, text=num, width=2, height=2)
    self.label3.grid(row=5, columnspan=10, sticky=W+E+N+S )

好的,截图看起来是这样的:

在这里输入图片描述

所以我需要做的是,在冒泡排序中,8 被交换到第一位后,我只需要给那些被交换的数字上色,而不是给所有数字上色。

3 个回答

0

这就是你想要的吗?希望这能对你有所帮助。

http://www.python-course.eu/tkinter_labels.php

self.label3 = Label(self, text=num, width=2, height=2, fg= "blue")
1

你有几种选择。第一种是为每个数字创建一个标签,这样你就可以单独给每个数字上色。第二种选择是使用一个文本控件。这个文本控件允许你给每个字符打标签,并且可以对这些标签应用不同的属性。比如,你可以有一个标签叫“移动”,然后为所有带有“移动”标签的字符设置前景色、背景色、字体等等。

想得开一点——一个控件虽然主要是用来输入的,但并不意味着它不能用来显示数据。

1

试着把这段代码调整到你的应用中去。
它使用了一个 Text 组件,并通过标签来显示不同颜色的文字。所以,你应该把你的 Label 组件换成 Text 组件。

from Tkinter import *

class Sorting(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Sorting")
        self.master.rowconfigure(5, weight=1)
        self.master.columnconfigure(5, weight=1)
        self.grid(sticky=W+E+N+S )

        nums = [10, 20, 8, 5, 7]       # example of entry
        result = sorted(nums)          # sorted result = [3 ,5 , 8, 10 ,20]

        # the color list holds the items changing position when sortened
        color = [ind for ind, (x, y) in enumerate(zip(nums, result)) if x != y]

        entry_num = ''.join('%4i' % num for num in nums)
        sort_nums = ''.join('%4i' % num for num in result)

        l1 = Label(self,  text="entry", width=25, height=1)
        l1.grid(row=0, column=1, sticky=N)

        t_entry = Text(self,  width=25, height=2)
        t_entry.grid(row=1, column=1, sticky=N)
        t_entry.insert(END, entry_num)

        l2 = Label(self, text='sorted', width=25, height=1)
        l2.grid(row=2, column=1, sticky=N)

        t_sorted = Text(self,  width=25, height=2)
        t_sorted.grid(row=3, column=1, sticky=N)
        t_sorted.insert(END, sort_nums)

        t_sorted.tag_config('red_tag', foreground='red')

        for pos in color:
            a = '1.%i' % (4 * pos)
            b = '1.%i' % (4 * pos + 4)
            t_sorted.tag_add('red_tag', a, b)


if __name__ == "__main__":
    Sorting().mainloop()

enter image description here

撰写回答