class randomMachine(object): import random as rd import tkinter as tk from tkinter import messagebox def setWeight(self, weight): for k, v in weight.items(): for t in range(v): self.chanceList.append(k) def drawing(self): if (len(self.chanceList) <= 0): self.messagebox.showwarning('ERROR', '奖品数不够') else: r = self.rd.randrange(0, len(self.chanceList)) # 随机数 # print("随机数 : ", r) self.rd.shuffle(self.chanceList) # 打乱列表 res = self.chanceList.pop(r) self.messagebox.showinfo('开奖结果', res) print(res) def addPrize(self): try: if self.inputName.get() != None and self.inputName.get() != '': if self.inputChance.get()!= '' and isinstance(int(self.inputChance.get()), int): self.Chance = int(self.inputChance.get()) self.Name = self.inputName.get() self.weight[self.Name] = self.Chance self.setWeight(self.weight) self.weight = {} self.messagebox.showinfo('SUCCESS', '添加奖品成功!') self.inputName.delete(first=0, last='end') self.inputChance.delete(first=0, last='end') else: self.messagebox.showwarning('ERROR', '请输入一个整数!') else: self.messagebox.showwarning('ERROR', '请输入奖品名称!') except Exception as e: self.messagebox.showwarning(e) def checkPrize(self): if (len(self.chanceList) <= 0): self.messagebox.showinfo('ERROR', '没有奖品了') else: store = {} for tmp in self.chanceList: if store.get(tmp)!=None: store[tmp] += 1 else : store[tmp] = 1 message = '' for k, v in store.items(): message += k + '剩余 : ' + str(v)+ '个'+'\n' self.messagebox.showinfo('查询结果', message) def graphicsUI(self): self.window = self.tk.Tk(className='抽奖') # 窗口 self.nameTitle = self.tk.Label() self.nameTitle["text"] = "在此输入奖品名称" self.nameTitle.pack() self.inputName = self.tk.Entry() self.inputName.pack() self.chanceTitle = self.tk.Label() self.chanceTitle["text"] = "在此输入奖品个数" self.chanceTitle.pack() self.inputChance = self.tk.Entry() self.inputChance.pack() self.addButton = self.tk.Button() self.addButton["text"] = '添加' self.addButton["command"] = self.addPrize self.addButton.pack(side='left', padx=30) self.checkButton = self.tk.Button() self.checkButton["text"] = '查询剩余奖品' self.checkButton["command"] = self.checkPrize self.checkButton.pack(side='left') self.drawButton = self.tk.Button() self.drawButton["text"] = '开奖' self.drawButton["command"] = self.drawing self.drawButton.pack(side='right', padx=30) self.window.mainloop() def __init__(self): self.weight = {} self.chanceList = []if __name__ == "__main__": test = randomMachine() test.graphicsUI()