Conditional tkinter button

Viewed 137

I would like to make sure that the file button here is being clicked in the first place before others button is being clicked.

def open_file():
    tf = filedialog.askopenfilename(
        initialdir="C:\\Users\\ASUS\PycharmProjects\pythonProject",
        title="Open Text file",
        filetypes=(("Text Files", "*.txt"),)
        )
    pathh.insert(END, tf)
    tf = open(tf)  # or tf = open(tf, 'r')
    data = tf.read()
    file.insert(END, data)
    tf.close()

filebut = Button(root, text="Select File", justify='center', command=open_file, height=2, width=30, fg='black')
filebut.place(x=30, y=80)#240

So, whenever I choose a file, the path will be displayed here.

pathh = Entry(root, width=45)
pathh.place(x=30, y=140)

However, I would like to add something to the buttons below to prevent user from clicking it as they are required to choose a file in the first place before clicking the buttons below. Nonetheless, if they tend to press the button below before selecting a file, it should pop out an error message.

mostActiveAuthor = Button(root, text=" MOST ACTIVE AUTHOR", height=2, width=38, command=ACTIVE_AUTHOR, fg='blue')
mostActiveAuthor.place(x=30, y=180)

mostActiveDay = Button(root, text="    MOST ACTIVE DAY", height=2, width=38, command=ACTIVE_DAY, fg='red')
mostActiveDay.place(x=30, y=230)

timeHighlyActive = Button(root, text=" TIME HIGHLY ACTIVE", height=2, width=38, command=HIGHLY_ACT, fg='black')#35
timeHighlyActive.place(x=30, y=280)

maxNumOfWords = Button(root, text="MAX NUMBER OF WORDS", height=2, width=38, command=MAX_NUM, fg='brown')
maxNumOfWords.place(x=30, y=330)
2 Answers

My solution to this problem would be to have some kind of boolean variable, for example "fileSelected" set to False. Then, in open_file() function have it set to True. Use ['state'] attribute of Button to have it set to "disabled" if the value of fileSelected variable is "False". I hope this helped you out.

As another option, you can put the creation of the other buttons into the function executed by the first. So, they're not even there until after the user selects file.

Related