我用gui编写的冒泡排序代码是这样的:
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所以我想给交换了一步的元素上色,比如arrayj和arrayj+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排在第一位,所以我需要给被交换的数字上色,而不是全部。
发布于 2012-02-10 02:57:13
尝试将此代码调整为适合您的应用程序。
它使用带有标记的Text小部件来生成彩色文本。因此,您应该用Text替换您的Label小部件。
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()

发布于 2012-02-09 20:29:20
你至少有几个选择。第一种方法是为每个数字创建一个label小部件,以便可以对每个数字分别着色。第二种选择是使用单个文本小部件。文本小部件允许您标记单个字符,并将属性应用于这些标记。因此,例如,你可以有一个"moved“标签,并为所有带有"moved”标签的字符设置前景、背景、字体等。
稍微跳出框框考虑一下--仅仅因为小部件主要用于输入并不意味着它不能也用于显示数据。
发布于 2012-02-09 12:11:19
这是你想要的吗?我希望这能对你有所帮助。
http://www.python-course.eu/tkinter_labels.php
self.label3 = Label(self, text=num, width=2, height=2, fg= "blue")https://stackoverflow.com/questions/9205157
复制相似问题