In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "Python how to achieve a random raffle gadget". In daily operation, I believe many people have doubts about how to achieve a random raffle gadget in Python. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to realize a random raffle gadget in Python". Next, please follow the editor to study!
Let's first look at the effect:
1. Core function design
For the gadgets of the random lottery, it is necessary to import the list of people who participate in the lottery, and then select different types of awards to randomly select the winning list and export it.
So, simply disassemble the requirements and roughly sort out the following core functions:
List import
To avoid duplicate names, let's agree on the following points:
① imports the list file of the participants in the lottery (xlsx type file)
The first column of ② data is ID, and the second column is name
Reference format case
Selection of award type
The type of award refers to signs such as the first prize and the second prize. Here we have built-in special prize-sixth prize with a total of 7 options to choose from.
The number of people in this round
The number of people in this round refers to the number of winners drawn at one time in each lottery. The default value is 5.
① will prompt and show the number of unwinners when the number entered exceeds the remaining number of unwinners.
②: when the number entered is 0, it indicates that the wheel is empty, and it also needs to be terminated manually.
③ when the number entered is negative, there is no response when you click on the lottery.
④ prompts you to enter the correct number when you fill in a non-number
Rotation area in the lottery
It is used to display the list of people who take part in this round of lucky draw randomly.
Personnel list
When the correct personnel list file is selected, a list of personnel information is automatically displayed here.
Winning record
Record the type of award and the list of winners each time.
Start the lottery.
When ① starts the lottery, he will first judge whether the lottery setting meets the conditions, otherwise there will be relevant prompts.
Click to start the lucky draw in the ② lucky draw will remind you that it is in the lottery.
End
There is no response to click end when ① is not in the lottery.
Clicking the end in the ② draw will show the results of the draw.
Reset
① reset will erase the history of the lottery (including local documents, if necessary, suggest keeping a file on the winning list)
Clicking reset in the ② lucky draw will indicate that it is in the lottery.
③ non-raffle status click reset will prompt that the operation will delete the history, whether to confirm
Once the basic function points are confirmed, we begin to work on GUI design.
2. Design and implementation of GUI
Based on the function point, we simply use axure for UI layout design, and then through the GUI development library for design, here is still the use of pysimplegui, mainly simple and convenient.
Based on the GUI design, we code as follows:
NameList_column = [[sg.Text ("personnel list:")], [sg.Listbox (values= [], size= (20,10), key= "nameList")],] result_column = [[sg.Text ("winning record:")], [sg.Multiline (", size= (48,10), key=" result ", text_color=" DeepPink ")] ] # theme setting sg.theme ("SystemDefaultForReal") # layout setting layout = [[sg.Text ("Select the list of participants in the lottery:", font= ("Microsoft Yahue", 12)), sg.InputText (", key=" _ file ", size= (50,1), font= (" Microsoft Yahue ", 10), enable_events=True), sg.FileBrowse (" Open ", file_types= ((" Text Files "," * .xlsx "),), size= (10,1) Font= ("Microsoft Yahue", 11))], [sg.Frame [[sg.Text ("this round of awards:", font= ("Microsoft Yahue", 12)), sg.Combo (["Special prize", "first prize", "second prize", "third prize", "fourth prize", "fifth prize", "sixth prize"), font= ("Microsoft Yahue", 10) Default_value= "Special Prize", size= (15,5), key= "_ type"), sg.Text ("number of people in this round:", font= ("Microsoft Yahue", 12)), sg.InputText ("5", key= "_ num", size= (38,1), font= ("Microsoft Yahue", 10)], title= "Lottery setting", title_color= "red", relief=sg.RELIEF_SUNKEN Tooltip=, [sg.Multiline (size= (48,5), font= ("Microsoft Yahei", 18), text_color= "Blue", key= "luckyName", justification= "center"), [sg.Column (nameList_column), sg.Column (result_column)], [sg.Text ("operating instructions:", font= ("Microsoft Yahei", 12))] [sg.Text ("① first selects the list of people to participate in the lucky draw xlsx file, the list file contains the fields ID and name, and the winning list of ② will be stored in the folder where the gadget is located. Reset deletes history files ", font= (" Microsoft Yahei ", 10), sg.Text (", font= (" Microsoft Yahei ", 12), size= (5, 1), sg.Button (" start Lottery ", font= (" Microsoft Yahei ", 12), button_color=" Orange "), sg.Button (" end ", font= (" Microsoft Yahei ", 12), button_color=" red "). Sg.Button ("reset", font= ("Microsoft Acer", 12), button_color= "red"),],] # create window window = sg.Window ("lucky draw gadget" Author @ Wechat official account: you can call me Brother Cai, layout, font= (Microsoft Yahi, 12), default_element_size= (50,1))
It contains the following controls:
Text text
InputText input text box
FileBrowse file browsing
Multiline multiline text box
Combo drop-down box
Listbox list
Button button
It is important to note that there is a Frame component for layout nesting, which is a good way to modularize UI layout.
3. Function realization
In this case, three functions need to be implemented, namely, reading the personnel list, drawing lottery at random and saving the winning list.
3.1 read the list of personnel
Here, openpyxl is used to read the table data and get the values of certain columns. Because of the existence of the table header, the table header is not needed.
Def nameList (window): fileName = values ["_ file"] try: wb = openpyxl.load_workbook (fileName) active_sheet = wb.active names = [cell_object.value for cell_object in list (active_sheet.columns) [1]] [1:] ids = [cell_object.value for cell_object in list (active_sheet.columns) [0]] [1:] names = [name+ "_" + str (id_) for name Id_ in zip (names, ids)] window ["nameList"] .update (names) return names except: sg.popup ("Please choose a personnel list file in the correct format", title= "prompt",) 3.2. Random lottery
Since there are multiple people who need to be randomly selected at one time, random.sample () is used here. It should be noted that names needs to be removed from the list of winners in the parameters passed in.
Def Result (window, names): global is_run, luckyNames _ type = values ["_ type"] # current round award type _ num = int (values ["_ num"]) # current round number while True: randomName = random.sample (names K=_num) luckyName = ".join (randomName) window [" luckyName "] .update (luckyName) if not is_run: headers = [" Award "," list "] toCsv (headers, [_ type] * len (randomName), randomName Lucky) luckyNames = luckyNames + _ type+ ":" + luckyName+ "window [" result "] .update (luckyNames) return time.sleep (0.088) 3.3. Keep the list of winners
Here we use the method of csv library to append storage.
Def toCsv (headers, col1, col2, file): # append if present Create a new if os.path.exists (lucky): with open (lucky, "a", encoding= "utf_8_sig", newline= "") as csvfile: writer = csv.writer (csvfile) writer.writerows (zip (col1, col2)) else: with open (lucky, "w", encoding= "utf_8_sig") Newline= "") as csvfile: writer = csv.writer (csvfile) writer.writerow (headers) writer.writerows (zip (col1, col2))
After completing the core function, we implement the GUI interaction logic.
3.4. GUI interaction logic
There are two global variables, one of which is used to record the current raffle status, and the other is used to store information about the people who have won the prize. For more information about the interaction logic, you can combine the core functional requirements with the following code.
# initial state is_run = FalseluckyNames = "" # event loop while True: event, values = window.read () if event in (None, "close the program"): break if event = = "_ file": nameList (window) if event = = "start the lottery": if is_run: sg.popup ("lottery in progress" There is no need to repeat operations. " Title= "Tip") continue try: names = nameList (window) # personnel list _ num = int (values ["_ num"]) # current round number lucky = "winning list .csv" # winning list if os.path.exists ( Lucky): with open ("winning list .csv" "r" Encoding= "utf_8_sig") as f: reader = csv.reader (f) selectedNames = set ([I [1] for i in reader] [1:]) names_set = set (names)-selectedNames else: names_set = set (names) if len (names_set) > = _ num: Is_run = True _ thread.start_new_thread (Result (window, names_set) else: sg.popup (f "Please select the correct number of lottery winners (current {len (names_set)} unwinners)", title= "Tip") except: sg.popup ("Please select the correct number of lottery winners (do not exceed the total number)" Title= "prompt") elif event = "end": is_run = False elif event = = "reset": if is_run: sg.popup ("lottery in progress" Please wait for the reset after the lottery is over, title= "prompt") continue yes_no = sg.popup_yes_no ("reset will make the historical data clear, do you want to do this?" , text_color= "red", title= "prompt") if yes_no = = "Yes": try: os.remove (lucky) luckyNames = "window [" result "] .update (luckyNames) window [" luckyName "] .update (luckyNames) sg.popup (" raffle history has been reset. " Title= "Tip") except: sg.popup ("No raffle History.", title= "Tip") window.close ()
Based on this, we have completed the production of the random raffle gadget.
The startup page is as follows:
At this point, the study on "how to achieve a random lottery gadget in Python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un