2015-02-27 4 views
0

Я делаю простую игру викторины для своего школьного проекта, и у меня возникают проблемы с обновлением виджетов во время выполнения программы. Это часть программы может быть (я знаю, что это не очень умный код, но до сих пор он работает):Как обновить виджет?

EuQuestionFrame=Frame(root) 
EuQuestionFrame.pack() 

question=['question1', 'question2'] 

     a=['20 273', 'aa']   #Possible answers: first question-first column and second question-second column 
     b=['19 732', 'bb'] 
     c=['21 327', 'cc'] 
     d=['20 372', 'dd'] 
number=0 

class Questions: 
     def question(self): 
      q=Label(frame, text=question[number], font=('Arial Black', '14')).pack()   #Here program writes questions that I listed before. 

     def answers(self): 
      def correct(): 
       number=+1 

      #Here I want to update all widgets to question 2, in that way I will change number value. 

      def incorrect(): 
       print('incorrect') 

      x=[correct, incorrect] #Correct answers for first and second questions - one column for each question. Compare with possible answers I listed before. 
      y=[incorrect, correct] 
      z=[incorrect, incorrect] 
      v=[incorrect, incorrect] 

      a1= Button(EuQuestionFrame, text=a[number], width=10, activebackground='orange', 
         cursor="circle", command=x[number]) 
      a1.pack() 
      a2= Button(EuQuestionFrame, text=b[number], width=10, activebackground='orange', 
         cursor="circle", command=y[number]) 
      a2.pack() 
      a3= Button(EuQuestionFrame, text=c[number], width=10, activebackground='orange', 
         cursor="circle", command=z[number]) 
      a3.pack() 
      a4= Button(EuQuestionFrame, text=d[number], width=10, activebackground='orange', 
         cursor="circle", command=v[number]) 
      a4.pack() 

Есть ли функция (и если да, то как использовать), которые обновление виджеты? Я много работал над этим, но из-за отсутствия знаний о программировании я не смог найти решение.

+0

Надеюсь, это достаточно ясно. Я сделал это немного проще. Если что-то неясно, дайте мне знать. – Luka1

+0

Я думаю, что ваша 'правильная' функция не будет иметь никакого эффекта, так как' number' не 'global'. Кроме того, почему «номер», который, как представляется, является количеством правильных ответов, определяет, правильный или неправильный ответ на вопрос? –

+3

Чтобы изменить виджеты после создания, вы можете использовать 'widget.configure (options)' –

ответ

0

Я сделал это, чтобы все, что вам нужно сделать, это редактировать словари, поскольку я дал указание добавить больше вопросов; если у вас есть какие-либо вопросы, прокомментируйте это. Он готов к запуску:

from Tkinter import * #Tkinter; If you are using 3.x, change to tkinter, emphasis on all lowercase 
from ttk import Frame, Style #You need this for the frame and style; 
import random 
class Questions(Frame): 

    def __init__(self, parent): 
      global root 
      global question 
      global corinc 
      global number 
      global a 
      global b 
      global c 
      global d 
      global qA 
      global curbutton 
      global ques#Current Question to be asked 
      global inc#Incorrect tally 
      global cors#Correct tally 
      global qnumber#Number of current question 
      global qnum 

      question=StringVar() 
      question.set('Question 1')#Current Question Label Textvariable 

      a=StringVar() 
      b=StringVar() 
      c=StringVar() 
      d=StringVar() 

      corinc=StringVar() 
      corinc.set('')#Displays Correct or Incorrect, At first displays nothing 
      number=0#Number of Question - 1 
      #number=random.randint(0, len(curbutton)-1 #UNCOMMENT THIS to make selection random 

      qA={'What Is 5068.25 x 4?' : 'a', 'Which answer has an average of 5?' : 'c'} 
      ##Put questions in format 'question' : 'properanswerbuttontoclick'; see above example 

      curbutton={1: 'a:20 273b:19 732c:21 327d:20 372', 2: 'a:1,2,3,4,5b:1,2,3,4,5,6c:3,4,5,6,7d:1,0,2,9,3'} 
      ###^^^Put options in format questionnumber : 'a:firstoptionb:secondoptionc:thirdoptiond:fourthoption'! 
      ###Otherwise, this will not work properly! 

      ques=StringVar() 
      inc=0 
      cors = 0 
      qnumber=1 
      qnum=StringVar() 

      self.parent = parent 
      Frame.__init__(self, parent) 
      #Binding Goes here; eg parent.bind('<Return>, fun.ction) 
      self.initUI() 

    def new_question(self): 
     ques.set(qA.keys()[number])#qA.keys()[number] gets the key at the location number in the Dictionary qA 
     a.set(str(list(curbutton[number+1].split('a:')[1].split('b:'))[0]))#These Grab the values for the key number+1, and display the PROPERLY FORMATTED results 
     b.set(str(list(curbutton[number+1].split('b:')[1].split('c:'))[0]))#on the buttons 
     c.set(str(list(curbutton[number+1].split('c:')[1].split('d:'))[0])) 
     d.set(str(list(curbutton[number+1].split('d:'))[1])) 
     qnum.set(str(number)+'/' + str(len(curbutton)))#Displays questionnumber/totalquestions 
     self.update_idletasks 

    def initUI(self): 
     global corinc 
     global a1 
     global a2 
     global a3 
     global a4 

     self.parent.title("Quiz") 
     self.style = Style() 
     self.style.theme_use("clam") 
     self.new_question()#Sets the button and answer values 
     q=Label(textvariable=question)#Question Number 
     q.pack() 
     aq=Label(textvariable=ques)#Question being asked 
     ci=Label(textvariable=corinc)#Displays Correct or Incorrect 
     ci.pack() 
     aq.pack() 

     a1= Button(textvariable=a, width=10, bg='orange', 
        cursor="circle", command= lambda: self.check('a'))#lambda allows you to pass a function with arguments, e.g. self.check('a') instead of self.check 
     a1.pack()#             #It must be there if you are passing arguments 
     a2= Button(textvariable=b, width=10, bg='orange', 
        cursor="circle", command= lambda: self.check('b')) 
     a2.pack() 
     a3= Button(textvariable=c, width=10, bg='orange', 
        cursor="circle", command= lambda: self.check('c')) 
     a3.pack() 
     a4= Button(textvariable=d, width=10, bg='orange', 
        cursor="circle", command= lambda: self.check('d')) 
     a4.pack() 
     qnumb=Label(textvariable=qnum)#displays qnum, see line 46 
     qnumb.pack() 

    def correct(self): 
     global cors 
     global number 
     cors = cors+1#Adds to correct tally 
     number=number+1#changes question number 
     #number=random.randomint(number, len(curbutton)) 
     corinc.set('Correct')#displays correct 
     self.update_idletasks#UPDATES ALL WIDGETS 
     question.set('Question ' + str(number+1))#Sets question number e.g. Question 1 
     global qnumber 
     qnumber=qnumber+1 
     if qnumber == len(curbutton): 
      qnumber=len(curbutton) 
     qnum.set(str(number)+'/' + str(len(curbutton)))#See line 62 
     self.update_idletasks#Updates 
     try: 
      self.new_question()#Calls New question function 
     except IndexError:#If it raises the error IndexError, it means there are no more q/a's listed and it will direct to 
      self.quiz_complete()#Completion 'Page' 

    def quiz_complete(self): 
     question.set('Quiz Complete') 
     corinc.set('Correct: ' + str(cors) + '\nIncorrect: ' + str(inc))#Take a guess 
     ques.set('') 
     a.set('Quit') 
     a1.configure(command=self.quitq) 
     b.set('Take Quiz Again') 
     a2.configure(command=self.restart) 
     c.set('') 
     d.set('') 
     self.update_idletasks 

    def restart(self): 
     self.update_idletasks 
     global number 
     corinc.set('') 
     question.set('Question 1') 
     a1.configure(command= lambda : self.check('a')) 
     a2.configure(command= lambda : self.check('b')) 
     global cors 
     cors=0 
     global inc 
     inc=0 
     number=0 
     #number=random.randint(0, len(curbutton)-1) 
     self.new_question() 
    def incorrect(self): 
     global inc 
     inc=inc+1#adds to incorrect tally 
     corinc.set('Incorrect') 
     self.update_idletasks 
    def check(self, awn): 
     if awn==qA.values()[number]: self.correct()#This checks if the value at location number matches the correct answer given on the qA dict 
     else: self.incorrect()#^^ 
    def quitq(self): 
     quit() 

def main(): 
    global root 
    root = Tk() 
    #root.iconbitmap(default='Drive:/Pythonpath/icon.ico')#Wont work for me but you can try it 
    root.geometry("300x200+100+100")#In format widthxheight+distancefromtop+distancefromleftside 
    app = Questions(root) 
    root.mainloop() 

main() 
Смежные вопросы