2012-02-04 28 views
0

我已经编写了这个代码,并且在这个函数中gen()id用于随机生成数字进行排序。我的代码是这样我想让你的gui应用程序在python中用Tkinter排序

from Tkinter import * 
import random 

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) 

     #label for sort intro  
     self.label1 = Label(self, text = "Select Sort", width = 25 , height=2) 
     self.label1.grid(row = 0, column = 1, sticky = N) 

     #Radio buttons for sorts 
     self.button1 = Radiobutton(self, text = "Bubble Sort") 
     self.button1.grid(row = 1, column = 0, sticky = W+E+N+S) 

     self.button2 = Radiobutton(self, text = "Quick Sort") 
     self.button2.grid(row = 1, column = 1, sticky = W+E+N+S) 

     self.button3 = Radiobutton(self, text = "Shell Sort") 
     self.button3.grid(row = 1, column = 2, sticky = W+E+N+S) 

     #label to store value 
     def gen(): 
     for x in range(0,10): 
      num=random.randint(0,100) 
      self.label2 = Label(self,text='%s'%num, width = 2, height = 2) 
      self.label2.grid(row =3 , columnspan =10 , sticky = W+E+N+S) 

     #button to generate number 
     self.button4 = Button(self,text='Generate no.', command=gen) 
     self.button4.grid(row = 2,column=1, sticky = W+E+N+S) 
     self.rowconfigure(5, weight = 1) 
     self.columnconfigure(5, weight = 1) 

def main(): 
    Sorting().mainloop() 

if __name__ == "__main__": 
    main() 

我想用它来产生随机数,然后对它们进行排序。任何建议去做。

+0

1),你应该更好地解释你想获得什么。草图会有所帮助。 2)你想编辑你的代码并修复缩进错误。 – joaquin 2012-02-04 21:46:09

+0

我编辑了它,你现在可以检查它 – 2012-02-04 23:43:41

+0

它还没有很好地缩进。如果你使用标准的4个空格缩进而不是2个,如果你觉得问题更加明显。这是遵循PEP-8风格指导建议的优势的实际证明。 – joaquin 2012-02-05 05:45:29

回答

3

试试这个:

#label to store value 
    def gen(): 
     self.nums = [] 
     for x in range(0, 10): 
      self.nums.append(random.randint(0, 100)) 
     # . . . . . . . . . . . <- maybe here call sorting method on self.nums 
     num = ''.join('%4i' % num for num in self.nums) 
     self.label2 = Label(self, text=num, width=2, height=2) 
     self.label2.grid(row=3, columnspan=10, sticky=W+E+N+S) 

排序的值存储在self.nums。在将标签显示在列表中之前,您希望将您的排序算法调用到该列表中。

enter image description here

我试图让你的代码,因为它是尽可能多地。从这一点可以进一步优化。例如,你可以代替:

self.nums = [] 
    for x in range(0, 10): 
     self.nums.append(random.randint(0, 100)) 

self.nums = [random.randint(0, 100) for x in range(10)] 
+0

thnx我会尝试 – 2012-02-05 06:17:17

+0

thanx很多它为我工作...... thanx – 2012-02-05 07:12:58

+1

@ user1155111完美!看到我最后的编辑也。您应该接受最好的答案(点击投票箭头下面的标记)。你还没有接受你对其他问题的答案。 – joaquin 2012-02-05 07:34:21

相关问题