我,一位Python初学者,利用Python中的tkinter、random 等知识,制作了一个简易的随机点名程序。
代码如下:
from tkinter import *
import tkinter as tk
import time
import random
condition=True
list=[]
with open('names.txt','r',encoding='UTF-8') as file:
_=file.readlines()
for name in _:
list.append(name.strip())
win = tk.Tk()
win.title("随机点名")
win.geometry("350x150")
entry1 = tk.Entry(win,width=10,bg="#ddff95")
entry1.insert(0,"请点击开始")
entry1.place(x=0,y=0,width=350,height=75)
def start():
global condition
condition = True
while condition:
entry1.update()
entry1.delete(0,"end")
entry1.insert(0, random.choice(list))
time.sleep(0.2)
def stopstopstop():
global condition
condition=False
b01 = Button(win, text="开始",bg="#b8f1ed",command = start).place(x=0,y=75,width=175,height=75)
b02 = Button(win, text="停!",bg="#f1b8f1",command = stopstopstop).place(x=175,y=75,width=175,height=75)
win.mainloop()
在编程过程中,遇到了一些问题:一开始在编写程序时,在函数中改动condition变量的时候,并没有声明要改动全局变量condition(没有写global condition),于是导致condition变量修改不生效,停止的按钮无法使变化中的名字停下来。这一点是所有python初学者都需要特别注意的。