问题描述
限时送ChatGPT账号..我的冒泡排序代码在 gui 中是这样的:-
My code for bubble sort is in gui is this:-
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] 这样交换一步的元素着色.
So i want to colour elements which are swaped for one step like array[j] and array[j+1] are swapped.
用于排序按钮并存入标签的函数是
The function used for sorting button and storing it into label is
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 后排在第一位,所以我需要为不是全部交换的数字着色.
so what i have to do is like after swapping in bubble sort 8 has come to first place so i need to colour the numbers which are being swapped not all.
推荐答案
尝试使此代码适应您的应用程序.
它使用带有标签的 Text
小部件来生成彩色文本.因此,您应该将 Label
小部件替换为 Text
.
Try to adapt this code to your application.
It uses a Text
widget with tag's to produce colored text. So, you should substitute your Label
widgets with 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()
这篇关于用于排序的 GUI:如何在排序的每个步骤中为某些数字着色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论