as I say in the title, when I click on a button (analyse) another windows open and I don't want it. The problems is, in the analyse function, the first line is an import of my tkinter file.
Thanks in advance for any help.
I tried to delete the import and the second windows does not pop up, so I am pretty sure it is the problem. Moreover I need to do this import in the analyse function because I already import the other module in my tkinter file
tkinter file :
import fileb
def analyser():
output=fileb.analyse(name)
fenetre = Tk()
fenetre.geometry("800x500")
label = Label(fenetre, text='Emotion Video')
label.pack()
boutonanalyse=Button(fenetre, text='analyze', command=analyser)
boutonanalyse.pack(side=BOTTOM)
fileb :
def analyse(name):
import tkinter_essais
When you import your Tkinter file, you are running that file. This means that the code is run twice and so you have two windows opened up. A way to bypass this is by putting your tkinter setup into a function, and having that run if it is the main program only using something like this:
import fileb
def analyser():
output=fileb.analyse(name)
def tkSetup():
fenetre = Tk()
fenetre.geometry("800x500")
label = Label(fenetre, text='Emotion Video')
label.pack()
boutonanalyse=Button(fenetre, text='analyze', command=analyser)
boutonanalyse.pack(side=BOTTOM)
if "__name__" == "__main__":
tkSetup()
The if name == main checks if the program is being run originally (best way I can think to describe it) and so it wont be run if you import the file.
Related
I'm working on a database GUI in tkinter but whenever I try to nest some functions inside one another it always makes unpredictable problems, So I'd like to ask if it's possible to make a button run a function that checks for a condition and if it's true it runs another script.py file that opens another window. Is that possible
I've already tried to press them into one file but weird problems appear and the file is too big to post here so I'm looking for a simpler solution
I'm a beginner so I'm not a hundred percent certain but I think it would look something like this
from tkinter import *
if name.get() == user_name AND pword.get() == password:
r = Tk()
my_btn = Button(r, text= "submit",command = open_py)
my_btn.grid(row=0,column=0)
r.mainloop()
Is this kind of thing possible or not.
How would "open_py():" look like
You can move the code of the new window to a different python file and import it.
For example:
import tkinter as tk
def open_dialog():
root = tk.Tk()
button = tk.Text(root, text="Hello!")
button.pack(root)
root.mainloop()
if __name__ == "__main__":
open_dialog()
in hello_dialog.py
import tkinter as tk
from hello_dialog import open_dialog
def main():
root = tk.Tk()
button = tk.Button(root, text="Start!", command=open_dialog)
button.pack(root)
root.mainloop()
in main.py
Both files need to be in the same folder. You can run main.py and it will run just fine even though the code for the Button showing "Hello!" is in a different file. All python files are libraries that you can import functions, classes and variables from. By adding if __name__ == "__main__" you can test whether your function was started directly or if it was imported by another program. To learn more about __name__ and importing other python files take a look at What does if __name__ == "__main__": do?.
I have my principal script running with terminal that works perfectly. Im trying to make a gui for it but im stuck at this point.
Like you see on the screen, at the start of the script it asks if it should check the database. And just after, it asks first the platform before opening the captcha for the database check. The problem happens exactly here on my GUI version, look.
Like you see, the gui starts, but when i click on check for new database, it directly opens the captcha without asking the platform... And it asks me the platform only after i solved the captcha which i dont want to after...
Here is the main testkinter.py code:
import tkinter as tk
from tkinter import messagebox
import commands
import CheckDatabase
import SetPlatformfile
def check_and_hide():
CheckDatabase.db_download(root)
checkdb.pack_forget()
checkdb1.pack_forget()
root = tk.Tk()
checkdb = tk.Button(root, text="Check for new databases", command=check_and_hide)
checkdb.pack()
checkdb1 = tk.Button(root, text="No")
checkdb1.pack()
root.mainloop()
Here is the set_platform function called in the Checkdatabse file:
import tkinter as tk
import config
from tkinter import messagebox
def set_platform(root):
platform = tk.Label(root,text="'a'|Android -- 'i'|iOS: ")
platform.pack()
androidbutton=tk.Button(root,text="Android",command=renameplatformandroid)
iosbutton=tk.Button(root,text="iOS",command=renameplatformios)
androidbutton.pack()
iosbutton.pack()
def renameplatformandroid():
config.platform = 'android'
print(config.platform)
def renameplatformios():
config.platform = 'ios'
print(config.platform)
And cuz of my checkdatabase file is really really long, i'll just put a screen at the exact moment where set_platform is called (its called in the func signup which itself is directly called at the beginning of db_download) .
I hope my question is clear! Let me know if you need more details.
I am new to Tkinter,
I have a program which takes CSV as input containing, outlet's geo-location,
display it on a map, saving it as HTML.
format of my csv:
outlet_code Latitude Longitude
100 22.564 42.48
200 23.465 41.65
... and so on ...
Below is my python code to take this CSV and put it on a map.
import pandas as pd
import folium
map_osm = folium.Map(location=[23.5747,58.1832],tiles='https://korona.geog.uni-heidelberg.de/tiles/roads/x={x}&y={y}&z={z}',attr= 'Imagery from GIScience Research Group # University of Heidelberg — Map data © OpenStreetMap')
df = pd.read_excel("path/to/file.csv")
for index, row in df.iterrows():
folium.Marker(location=[row['Latitude'], row['Longitude']], popup=str(row['outlet_code']),icon=folium.Icon(color='red',icon='location', prefix='ion-ios')).add_to(map_osm)
map_osm
This will take display map_osm
Alternate way is to save map_osm as HTML
map_osm.save('path/map_1.html')
What I am looking for is a GUI which will do the same thing.
i.e prompt user to input the CSV, then execute my code below and display result
or at least save it in a location.
Any leads will be helpful
You question would be better received if you had provided any code you attempted to write for the GUI portion of your question. I know (as well as everyone else who posted on your comments) that tkinter is well documented and has countless tutorial sites and YouTube videos.
However if you have tried to write code using tkinter and just don't understand what is going on, I have written a small basic example of how to write up a GUI that will open a file and print out each line to the console.
This won't right out answer your question but will point you in the right direction.
This is a non-OOP version that judging by your existing code you might better understand.
# importing tkinter as tk to prevent any overlap with built in methods.
import tkinter as tk
# filedialog is used in this case to save the file path selected by the user.
from tkinter import filedialog
root = tk.Tk()
file_path = ""
def open_and_prep():
# global is needed to interact with variables in the global name space
global file_path
# askopefilename is used to retrieve the file path and file name.
file_path = filedialog.askopenfilename()
def process_open_file():
global file_path
# do what you want with the file here.
if file_path != "":
# opens file from file path and prints each line.
with open(file_path,"r") as testr:
for line in testr:
print (line)
# create Button that link to methods used to get file path.
tk.Button(root, text="Open file", command=open_and_prep).pack()
# create Button that link to methods used to process said file.
tk.Button(root, text="Print Content", command=process_open_file).pack()
root.mainloop()
With this example you should be able to figure out how to open your file and process it within a tkinter GUI.
For a more OOP option:
import tkinter as tk
from tkinter import filedialog
# this class is an instance of a Frame. It is not required to do it this way.
# this is just my preferred method.
class ReadFile(tk.Frame):
def __init__(self):
tk.Frame.__init__(self)
# we need to make sure that this instance of tk.Frame is visible.
self.pack()
# create Button that link to methods used to get file path.
tk.Button(self, text="Open file", command=self.open_and_prep).pack()
# create Button that link to methods used to process said file.
tk.Button(self, text="Print Content", command=self.process_open_file).pack()
def open_and_prep(self):
# askopefilename is used to retrieve the file path and file name.
self.file_path = filedialog.askopenfilename()
def process_open_file(self):
# do what you want with the file here.
if self.file_path != "":
# opens file from file path and prints each line.
with open(self.file_path,"r") as testr:
for line in testr:
print (line)
if __name__ == "__main__":
# tkinter requires one use of Tk() to start GUI
root = tk.Tk()
TestApp = ReadFile()
# tkinter requires one use of mainloop() to manage the loop and updates of the GUI
root.mainloop()
I am wondering on how I can create a restart button that once clicked, can restart the entire script. What I thought was that you destroy the window then un-destroy it but apparently there is no un-destroy function.
I found a way of doing it for a generic python program on this website: https://www.daniweb.com/programming/software-development/code/260268/restart-your-python-program. I wrote an example with a basic tkinter GUI to test it:
import sys
import os
from tkinter import Tk, Label, Button
def restart_program():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
python = sys.executable
os.execl(python, python, * sys.argv)
root = Tk()
Label(root, text="Hello World!").pack()
Button(root, text="Restart", command=restart_program).pack()
root.mainloop()
The following solution works as well but is quite harsh, i.e. the entire environment is lost.
# kills the whole application and starts a fresh one
def restart():
root.destroy()
root = Tk()
root.mainloop()
I would Like to Use this Function:-
First of All Import os Module
import os
Then Use this Code:-
# Restarts the Whole Window
def restart():
root.destroy()
os.startfile("main.py")
Or if You want no console behind then Simply Change the extension of the file to .pyw
And Run this Code:-
# Restarts the Whole Window
def restart():
root.destroy()
os.startfile("main.pyw")
When running a tkinter program in the standard python idle program the window displays and you are able to interact with it, yet running the same program in pycharm causes the program window to flash up briefly then close.
I'm assuming its to do with the mainloop, what do you need to modify in your code to prevent the program from automatically closing when running in pycharm
An excert from my code follows
from tkinter import *
import tkinter
from tkinter import Text, Tk, ttk
import csv
from csv import DictReader
import sys
import os
class GUI:
def __init__(self, root):
....
def main():
global label
root = Tk()
root.title(" My program")
root.geometry("550x330+600+300")
mycolor = '#%02x%02x%02x' % (39, 39, 39) # background color
root.configure(bg=mycolor)
gui = GUI(root)
main()
Update : After a bit of mucking around, partly due to my code not being the best (rookie), I've managed to get it to work. For anyone interested heres the modification:
from tkinter import *
import csv
from csv import DictReader
import sys
import os
class GUI:
def __init__(self, master):
self.master = master
master.title(" My Programs")
master.geometry("550x330+600+300")
master.iconbitmap('logo.ico')
mycolor = '#%02x%02x%02x' % (39, 39, 39) # background color
master.configure(bg=mycolor)
....... Most of the above is program set up stuff but shown
MAIN CODE HERE
root = Tk()
gui = GUI(root)
root.mainloop()
Works now as expected
Python has a -i startup option which cause Python to enter interactive move when the program finishes, instead of exiting. IDLE executes code as if one entered python -i file.py at the terminal. This allows one to interactively explore the live gui by entering code in the Shell.
From this question and the one referenced by flyingmeatball, it appears that PyCharm does not use or simulate -i. So one must finish a tkinter program with root.mainloop to see anything. Unless one adds a button to quit the mainloop without destroying the application, one will not be able to interact with interactive statements. (Again, this is completely based on what has been posted on SO, as I have no experience with PyCharm.)