2017-08-28 36 views
2

我是Python编程新手,我正在学习如何创建用户界面。我想创建一个非常基本的界面,它具有以下流程:使用while循环,界面显示问题列表中包含的所有问题。每次提出问题时,问题下都会出现两个按钮(是否)。只有当其中一个点击时,界面会显示下一个问题。 我附上我试过的代码。使用按钮更改问题

import tkinter as tk 

questions=['Question 1','Question 2','Question 3','Question 4', 'Question 5'] 
root = tk.Tk() 
root.minsize(300, 300) 
answers=['Yes','No'] 
b_list = [] 

def ask(): 
    count=0 
    while count<len(questions): 
     lab=tk.Label(root,text=questions[count]) 
     lab.pack() 
     count+=1 

for i in range(2): 
    b = tk.Button(root, text = answers[i],command=ask) 
    b.grid(row = 0, column = i) 

    b_list.append(b) 

root.mainloop() 

这样的代码根本不起作用。我想我也是在while循环中犯了一个错误,要求显示所有问题,而不是一次性显示。任何想法使这样的代码工作? 感谢您的时间!

+0

首先,所有按钮都不会显示,直到while循环结束。所以你需要将for循环移到while循环中。 –

回答

2

主要有两个原因使您的代码不运行:

  1. 在一个脚本,你不能有两个以上的几何经理写的GUI。这不仅适用于tkinter,也适用于PyQt等其他GUI第三方库。
  2. 标签应该在每一轮中显示不同的消息或问题。所以这意味着你需要修改内容StringVar。它表现为字符串的变量。您可以了解更多here

我不清楚为什么要存储按钮以及保存用户所做结果的位置。

这里是我的代码:

import tkinter as tk 

questions = ['Question 1', 'Question 2', 
      'Question 3', 'Question 4', 'Question 5'] 
answers = ['Yes', 'No'] 


root = tk.Tk() 
root.minsize(300, 300) 


def ask(): 
    if questions: 
     lab_text.set(questions.pop(0)) 

for index, answer in enumerate(answers): 
    lab_text = tk.StringVar() 
    lab = tk.Label(root, textvariable=lab_text) 
    lab.grid(row=0, column=0) 
    b = tk.Button(root, text=answer, command=ask) 
    b.grid(row=1, column=index) 

#initialize label 
ask() 


root.mainloop() 
1

这也可以在一个面向对象的方式可以撑起未来打样做得更好。

请参阅我的评论下面的脚本版本的解释和示例:

from tkinter import * 
import random 

class App: 
    def __init__(self, root): 
     self.root = root 
     self.array = ["Question1", "Question2", "Question3", "Question4", "Question5"] #list containing questions 
     self.answer = [] #empty list for storing answers 
     self.question = Label(self.root, text=self.array[len(self.answer)]) #creates a text label using the element in the 0th position of the question list 
     self.yes = Button(self.root, text="Yes", command=self.yescmd) #creates button which calls yescmd 
     self.no = Button(self.root, text="No", command=self.nocmd) #creates button which calles nocmd 
     self.question.pack() 
     self.yes.pack() 
     self.no.pack() 
    def yescmd(self): 
     self.answer.append("yes") #adds yes to the answer list 
     self.command() #calls command 
    def nocmd(self): 
     self.answer.append("no") #adds no to the answer list 
     self.command() #calls command 
    def command(self): 
     if len(self.answer) == len(self.array): #checks if number of answers equals number of questions 
      self.root.destroy() #destroys window 
      print(self.answer) #prints answers 
     else: 
      self.question.configure(text=self.array[len(self.answer)]) #updates the text value of the question label to be the next question 
root = Tk() 
App(root) 
root.mainloop() 

这基本上是只有在我们只是配置label显示在问题的下一个元素的意义不同list而不是销毁它或弹出list