I'm trying to:
- open a file and randomly pick values and display them in textbox on 1st click of a button,
- then on every subsequent clicks of same button on display new random values — without new prompts for opening file.
My Script:
from tkinter import *
from tkinter import filedialog
from random import sample
root = Tk()
root.title('Name Picker')
root.iconbitmap('c:/myguipython/table.ico')
root.geometry("400x400")
text_file = 0
step1 = text_file
somebool = False
def handler():
if somebool == False:
open_txt()
pick()
elif somebool == True:
pick()
def open_txt():
global text_file
text_file = filedialog.askopenfilename(initialdir="C:/myguipython/", title="Open Text File", filetypes=(("Text Files", "*.txt"), ))
name = text_file
name = name.replace("C:/myguipython/", "")
name = name.replace(".txt", "")
text_file = open(text_file, 'r')
somebool = True
def pick():
global text_file
step1=text_file.read().strip('"').split('","')
step2=[]
for a in step1:
step2.append(a)
print(step2)
entries_into_list = step2
number_of_items = 2
string_data = [str(data) for data in step2]
rando = sample(string_data, number_of_items)
rando1 = sample(string_data, number_of_items)
my_text.delete(1.0, END)
my_text.insert(INSERT, " ".join(rando + rando1))
topLabel = Label(root, text="Picked Names", font=("Helvetica", 24))
topLabel.pack(pady=20)
winButton = Button(root, text="pick names", font=("Helvetica", 24), command=handler)
winButton.pack(pady=20)
my_text = Text(root, width=40, height=10, font=("Helvetica", 18))
my_text.pack(pady=10)
root.mainloop()
I used with handler()
and command=handler
and somebool
from those ideas
How to control the events of clicking on a button in tkinter
Using global variables in a function
On 1st he script prompts a 1st time and displays random 1st draws as intended,
but on subsequent clicks it still prompts for file opening despite somebool
set to True
at end of open_txt()
function (Handler should not run it again after 1st time, I expect only pick()
to run when somebool
set to True
).
Why it is open_txt()
still running after somebool
set to True
? Your help is appreciated.