I want to launch an "Open File" dialog in Tkinter in Python 2.7.
My code starts with:
from Tkinter import Frame, Tk, BOTH, Text, Menu, END
import tkFileDialog as tkfd
import fileinput
root = Tk()
global strTab
strTab = ""
def openTab(event):
r = tkfd.askopenfilename()
strTab = unicodedata.normalize('NFKD', r).encode('ascii','ignore')
Later in the code I have:
btnLoadTab = Button(root,
text="Load Tab",
width=30,height=5,
bg="white",fg="black")
btnLoadTab.bind("<Button-1>", openTab)
btnLoadTab.pack()
root.mainloop()
When I press the button an "Open File" dialog is shown, but when I select a file it closes and the button remains "clicked".
If I later call to strTab outside of openTab, it remains equal to "".
You can find workable example here: http://www.python-course.eu/tkinter_dialogs.php
Related
I have created a vocabulary journal by using Tkinter, and I am struggling to pop a window that i created already.
Since i am a beginner, I have not really used class everywhere..
project/build/gui.py
def open_new():# button command
print("clicked")
button_1 = Button(
image=button_image_1,
borderwidth=0,
highlightthickness=0,
command=open_new,
relief="flat"
)
I have created another window in another directory
project/build/build2/gui.py
from db import Database
from pathlib import Path
from tkinter import messagebox
from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage,Frame
ob=Database('store.db')
def add_values():
if entry_1.get()=='' or entry_2.get()=='':
messagebox.showerror('no value','please enter anu words')
return
ob.insert(entry_1.get(),entry_2.get())
# print(ob.fetch())
messagebox.showinfo("value has been added", "successfully added")
window = Tk()
blah blah
....
window.mainloop()
WhatI want to do is pop up the second module, which is actually a window. I do not think , it is possible to pop up this window by using toplevel(), is it?
So which code should i use to pop up it?
I am trying to restart my main GUI/Halt the program flow when I Click on the "X" button in my tkinter messagebox . Any idea how can I do this ?
PS: I have read the many threads about closing the main GUI itself but nothing specific to messagebox
By default , my code proceeds to ask me for an output path using the filedailog.askdirectory() method when clicking "ok", or on closing the messagebox
My message box and the main GUI in the background
There's no simple way to add a custom handler to the "X" button. I think it's better to use messagebox.askokcancel() variation of messageboxes instead of showinfo, and halt the program if the returned result is False:
import tkinter as tk
from tkinter import messagebox, filedialog
root = tk.Tk()
def show_messagebox():
result = messagebox.askokcancel("Output path", "Please select an output file path")
if result:
filedialog.askdirectory()
else:
messagebox.showinfo("Program is halted")
tk.Button(root, text="Show messagebox", command=show_messagebox).pack()
root.mainloop()
Or, even simpler, you can just show filedialog.askdirectory() directly. If the user doesn't want to choose directory, they can click on the "Cancel" button, and then the program checks if there was empty value returned, and halts if so:
import tkinter as tk
from tkinter import messagebox, filedialog
root = tk.Tk()
def show_askdirectory():
directory = filedialog.askdirectory(title="Please select an output file path")
if not directory:
messagebox.showinfo(message="The program is halted")
else:
messagebox.showinfo(message="Chosen directory: " + directory)
tk.Button(root, text="Choose directory", command=show_askdirectory).pack()
root.mainloop()
im new topython 2.7 and want to know if it is possible to open a tkinter messagebox with a button combination on keyboard (Ctrl+alt+'something')
that pops up like an windows error message
import win32api
import time
import math
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def Message():
tkMessageBox.showinfo("Window", "Text")
for i in range(9000):
x = int(600+math.sin(math.pi*i/100)*500)
y = int(500+math.cos(i)*100)
win32api.SetCursorPos((x,y))
time.sleep(.01)
Yes, you can bind to control and alt characters. Bindings are fairly well documented. Here's one good source of information:
http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
As an example, to bind to ctrl-alt-x you would do this:
top.bind("<Control-Alt-x>", Message)
You can bind to a sequence of events by specifying the whole sequence. For example, if you wanted to implement a cheat code you could do something like this:
label.bind("<c><h><e><a><t>", Message)
For letters, "a" is the same as "<a>", so you can also do this:
label.bind("cheat", Message)
Here is a complete working example:
import Tkinter as tk
import tkMessageBox
def Message(event=None):
tkMessageBox.showinfo("Window", "Text")
def Cheat(event=None):
tkMessageBox.showinfo("Window", "Cheat Enabled!")
root = tk.Tk()
label = tk.Label(root, text="Press control-alt-m to see the messagebox\ntype 'cheat' to enable cheat.")
label.pack(fill="both", expand=True, padx=10, pady=100)
label.bind("<Control-Alt-x>", Message)
label.bind("<c><h><e><a><t>", Cheat)
label.focus_set()
root.mainloop()
If you want something like: Press button A, then press button B then open a Message box it is possible.
Do something like:
from Tkinter import *
import tkMessageBox
def change():
global switch
switch=True
def new_window():
if switch:
tkMessageBox.showinfo("Random name", "Correct combination")
else:
print "Not the correct order"
root = Tk()
switch = False
root.bind("<A>", change)
root.bind("<B>",new_window)
root.mainloop()
If you want more buttons then use an integer and increase it while using switches for the correct button order.
Note that you can bind key combinations as well with root.bind("<Shift-E>") for example
Edit: Now a and b keyboard button insted of tkinter buttons
trying to make a GUI with an 'open file' button. When I run the code shown below, the open file dialog opens straight away, and not when I press the button. Why? Is there a simple way to fix this that doesn't involve using classes? (I don't currently know anything about classes and am working on a time-pressured project)
from tkinter import *
interface = Tk()
def openfile():
return filedialog.askopenfilename()
button = ttk.Button(interface, text = "Open", command = openfile())
button.grid(column = 1, row = 1)
interface.mainloop()
The code is passing the return value of the openfile function call, not the function itself. Pass the function itself by removing trailing () which cause a call.
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
interface = Tk()
def openfile():
return filedialog.askopenfilename()
button = ttk.Button(interface, text="Open", command=openfile) # <------
button.grid(column=1, row=1)
interface.mainloop()
in python's default editor, IDLE, it is possible to have multiple 'Open' dialogs opened at the same time.
I'm looking at their source, but I can't find where I can have this behavior replicated. from their IOBinding.py's :
from tkinter import filedialog as TkFileDialog
...
class IOBinding:
...
def askopenfile(self):
dir, base = self.defaultfilename("open")
if not self.opendialog:
self.opendialog = tkFileDialog.Open(master=self.text,
filetypes=self.filetypes)
filename = self.opendialog.show(initialdir=dir, initialfile=base)
return filename
so they do use tkinter's built-in filedialog module, but I can't find way to have some 'modeless' dialogs. I can have dialogs opened by two codes, which are basically same:
from tkinter import filedialog as tkFileDialog
file_name = tkFileDialog.Open( ... ).show()
file_name = tkFileDialog.askopenfilename()
but they blocks whole application - users cannot switch windows or issue new command until they close the dialog. also, I can't call these dialog functions from different thread - that will kill whole my Tk app. What should I do?
filedialog have parent option. You can change it to hidden window to prevent blocking the root window:
from tkinter import filedialog as tkFileDialog
from tkinter import *
def ask_open():
p = hidden if attach_to_hidden.get() else root
tkFileDialog.Open(parent=p).show()
root = Tk()
hidden = Toplevel()
hidden.withdraw()
attach_to_hidden = IntVar()
Checkbutton(root, text='Attach to hidden window', variable=attach_to_hidden).pack()
Button(root, text='Open', command=ask_open).pack()
root.mainloop()