从Tkinter按钮获取随机文本变量-python

时间:2018-07-13 14:06:04

标签: python tkinter

标题可能有些混乱,所以我将进一步描述我的问题。

我专门为自己编写了一个小程序,可以帮助我学习中文。这将有助于我进行编码,同时又可以帮助学习。

我遇到了从按钮获取文本变量的问题,而没有功能,代码工作得像想要的那样。但是,当尝试获取按钮上显示的随机文本时,这会导致我遇到问题,因为文本没有出现。我需要的是,当按下按钮时,功能会检查输入的字符是否相同,并给出正确/错误的提示。

我对编码并不陌生,因此可以很简单,但仍希望获得任何帮助。

代码:

#========== Imports ===========#

from tkinter import *
from tkinter import messagebox
import random

#========== Parameters ==========#

CN = Tk()
CN.title("Chinese Test")
CNW = ["爱","八","爸爸","杯子","北京","本","不客气","不","菜","茶","吃","出租车","打电话",
       "大","的","点","电脑","电视","电影","东西","都","读","对不起","多","多少","儿子",
       "二","饭店","飞机","分钟","高兴","个","工作","汉语","好","号","喝","和","很","后面","回","会","几","家","叫","今天"]
Cword = ""
Cent = StringVar()


def butPress():
    global Cword
    if (B0.text==Cword): #wrong way to get text
        messageText = "Correct"
    else:
        messageText = "Incorrect"

CNEntry = Entry(CN,textvariable = Cent).grid(row = 0, column = 1, columnspan = 8)

B0 = Button(CN, text = random.choice(CNW),command = lambda:butPress,bd = 3, width = 5, height = 3).grid(row = 6, column = 4, padx = 10, pady = 10)

#========== Pack ==========#

CN.mainloop(  )

1 个答案:

答案 0 :(得分:1)

有几件事。
首先,command = lambda:butPress不起作用。使用command = butPress。仅当需要传递不需要的参数(例如command = lambda:butPress(parameter))时,才应使用lambda。

然后是B0.text。因为你这样做

B0 = Button(...).grid(...)

B0None,因为这就是grid()返回的内容。更改为

B0 = Button(...)
B0.grid(...)

这样B0是一个Button对象。要获取当前文本,您不能使用B0.text,而必须使用B0['text']

然后将文本与Cword''进行比较,并且永远不变。如果要将其与“条目”中输入的文本进行比较,请使用CNEntry.get()(再次将grid放在另一行之后)。