适合初学者的随机点名程序

我,一位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初学者都需要特别注意的。

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值