效果图:
import tkinter as tk import random window = tk.Tk() window.geometry('400x400') window.title('四则运算题生成器') ysfh = ['+','-','*','/'] # ss表示算式变量,jg表示结果变量,da表示答案变量,sr表示输入变量 ss = tk.StringVar() ss.set('') jg = tk.StringVar() jg.set('') da = tk.StringVar() da.set('') sr = tk.StringVar() sr.set('') tk.Label(window,text='算式:',justify=tk.RIGHT,width=80).place(x=5,y=5,width=80,height=20) tk.Label(window,text='结果:',justify=tk.RIGHT,width=80).place(x=5,y=35,width=80,height=20) tk.Label(window,text='答案:',justify=tk.RIGHT,width=80).place(x=5,y=65,width=80,height=20) tk.Label(window,textvariable = ss).place(x=70,y=5) tk.Label(window,textvariable = jg).place(x=70,y=35) tk.Label(window,textvariable = da).place(x=70,y=65) select = tk.IntVar() #Radiobutton单选 tk.Radiobutton(window,text='加法',variable = select,value=0).place(x=50,y=170) tk.Radiobutton(window,text='减法',variable = select,value=1).place(x=150,y=170) tk.Radiobutton(window,text='乘法',variable = select,value=2).place(x=50,y=230) tk.Radiobutton(window,text='除法',variable = select,value=3).place(x=150,y=230) #评分 scores = tk.IntVar() scores.set(0) tk.Label(window,text='目前得分:').place(x=250,y=5) tk.Label(window,textvariable=scores).place(x=330,y=5) #Entry对话框 En = tk.Entry(window,width=10,textvariable = sr) En.place(x=150,y=5) #检查答案 def fun1(): b1.config(text='下一题') ss.set('') jg.set('') da.set('') sr.set('') ans = fun2() def fun1_1(temp): #这里要接受来自bind()的变量 sr_1 = En.get() if str(sr_1)==str(ans): jg.set('Correct') da.set(ans) temp = scores.get() temp +=1 scores.set(temp) else: jg.set('Wrong') da.set(ans) temp = scores.get() temp -=1 scores.set(temp) with open('./Yunsuan.txt','a',encoding='utf-8') as fp: temp = '式子: '+ss.get()+sr.get()+'\n' fp.write(temp) En.bind('<Key-Return>',fun1_1) #Return后跳转到fun1_1 def exit_(): window.destroy() b1 = tk.Button(window,text='生成题目',command = fun1) b1.place(x=60,y=120,width=50,height=20) b2 = tk.Button(window,text='退出',command = exit_) b2.place(x=180,y=120,width=50,height=20) #生成题目 def fun2(): index = select.get() n1 = random.randint(1,100) n2 = random.randint(1,100) result = 0 if index==0: result = n1+n2 elif index == 1: n1,n2 = max(n1,n2),min(n1,n2) result = n1-n2 elif index == 2: result = n1*n2 elif index == 3: if n1 == n2: result = 1 else: while n1%n2!=0: n1 = random.randint(1,100) n2 = random.randint(1,100) n1,n2 = max(n1,n2),min(n1,n2) result = int(n1/n2) temp = str(n1)+ysfh[index]+str(n2)+' =' ss.set(temp) return result window.mainloop()