import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Done!\n(click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.entrythingy = tk.Entry()
self.entrythingy2 = tk.Entry()
self.entrythingy.pack()
self.entrythingy2.pack()
# here is the application variable
self.contents = tk.StringVar()
self.contents2 = tk.StringVar()
# set it to some value
self.contents.set("stdio")
self.contents2.set("script name")
# tell the entry widget to watch this variable
self.entrythingy["textvariable"] = self.contents
self.entrythingy2["textvariable"] = self.contents2
self.text = tk.Text()
self.text.pack()
# and here we get a callback when the user hits return.
# we will have the program print out the value of the
# application variable when the user hits return
self.entrythingy.bind('<Key-Return>',
self.print_contents)
self.quit = tk.Button(self, text="QUIT", fg="red",
command=root.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
#print("hi there, everyone!")
self.fn = self.contents2.get()
self.body = self.text.get(1.0, tk.END).split('\n')
#print('Self.body:\n',self.body)
self.libs = self.contents.get().split(' ')
self.make_c()
def make_c(self):
lib_text = ''
for i in self.libs:
lib_text += "#include <lib.h>\n".replace('lib', i)
body_text = "int main() {\n\t"+"\n\t".join(self.body)+"return 0\n}"
print(lib_text+body_text)
with open(self.fn+'.c', 'w+') as f:
f.write(lib_text+body_text)
print('File written!')
from subprocess import call
call(['gcc',self.fn+'.c', '-o', self.fn])
def print_contents(self, event):
print("hi. contents of entry is now ---->",
self.contents.get())
#self.contents.set("")
#def
root = tk.Tk()
app = Application(master=root)
app.mainloop()
Those are the my code, which tries to make a c file and convert it. The problem is, when I convert it once, it is working fine, but when I change the content of the text box, the file doesn't change, and I don't understand why. I am sure that I put in the new file content, because it prints before it writes. Also, it appears that when I try to write files independent from tkinter, it works just the way I want it to.
I think there is some mechanism that I am not aware of in TK, or there is a bug. Please help me out, thanks.
I solved it. It doesn't compile again due to the error in it when I added return 0, without semicolon. So, when I click the executable file, it shows the old program. I added the semicolon, and now it is fine. Thx everyone!
Related
I am currently developing a program to try an xml file. However I encounter a problem that has been blocking me for a few days now and I can rack my brains my beginner level in python and my many research does not help me to get over it.
I first try to retrieve 1 element from my xml file. I can do it well only the graphics window that should normally display it does not generate and I have the following error message:
The error :
window.fenetre_text(Acte_D) NameError: name 'Acte_D' is not defined`
well my code is :
import tkinter as tk
from tkinter import *
from tkinter import messagebox
from tkinter.filedialog import askopenfilename
from xml.dom import minidom`
global file
global Acte_D
global element_A
global lines
class fenetreM(Tk):
#GUI
def __init__(self, master=None,*args, **kwargs):
Tk.__init__(self,master, *args, **kwargs)
self.menu_bar()
self.title("EssaiV1.0.1")
self.geometry("800x400")
self.minsize(380,140)
self.config(background='#F0F0F2')
#New_frame=Frame(fenetreM, bg='#abd7f4')`
def menu_bar(self):
menu_bar = Menu(self)
menu_file = Menu(menu_bar, tearoff=0)
menu_file.add_command(label="Open", underline=0, command=self.open_file)
menu_file.add_command(label="Affichage",underline=0,command=self.do_something)
menu_file.add_separator()
menu_file.add_command(label="Exit",underline=1,command=self.quit)
menu_bar.add_cascade(label="File",underline=0, menu=menu_file)
menu_help = Menu(menu_bar, tearoff=0)
menu_help.add_command(label="About", command=self.do_about)
menu_bar.add_cascade(label="Help",underline=0, menu=menu_help)
self.config(menu=menu_bar)
valid = False
return(valid)
def open_file(self):
types = [("All Files",".*")]
file = askopenfilename(title="File to open : ", filetypes=types)
print("Copy")
doc = minidom.parse(file)
print(doc.nodeName)
print(doc.firstChild.tagName)
Acte_D = doc.getElementsByTagName("ActeDescription")
print("\n")
element_A = (f" we have {Acte_D.length} element \n Version : ")
for i in Acte_D:
screen_1=(i.getAttribute("version"))
print(screen_1)
print("\n")
return (Acte_D)
def fenetre_text(self,Acte_D):
tk=Text(fenetreM, height = 10, width =100)
Fenetre_A=tk.inset(END,textvariable=self.element_A+Acte_D)
Fenetre_A.pack(side="top", fill="x", expand=True)
return(Acte_D)
window = fenetreM()
window.fenetre_text(Acte_D)
window.mainloop()
Can someone explain my mistake to me?
Thanks
I tried to graphically display the result of Acte_D in my window defined in my method fenetre_text.
But I can't.
When I provide an address /and or location to the entry bar and I press the "Get forecast" button the script fails at line 22. I think the error is raised because the str(address.get()) cant find the address variable, probably because it doesn't technically exist during that point of run time (I'm not able to log the error due to the structure of that function).
My question is; How do I make sure that my "get_hourly_forecast" function is able to access the address entry variable?
I have tried instantiating the address variable in various locations, e.g in the MainWeatherHub class, as well as in the MyWeatherApp class and then passing it as an argument to the MainWeatherHub in line 79, neither variation has worked. The current code shows the former variation.
import urllib, json, requests
from tkinter import *
from tkinter import ttk
def get_hourly_forecast(*args):
## params *args:
#A location argument
#Returns:
# A list of temps in Farenheit for the next 156 hours
API_KEY = 'removing my API key for security purposes'
try:
print('here') # The code makes it to here
curr_address = str(address.get()) # Code seems to fail here (not sure how to have the error print)
print('here')
geocode_url = "https://maps.googleapis.com/maps/api/geocode/json?address={}&key={}".format(cur_address, API_KEY)
response = requests.get(geocode_url)
response_dict = response.json()['results']
location = response_dict[0]['geometry']['location']
lat = location['lat']
lng = location['lng']
local_url_request = 'https://api.weather.gov/points/lat={}lng={}'.format(lat, lng)
response_one = requests.get(local_url_request)
json_dict_one = response_one.json()
local_props = json_dict_one['properties']
local_forecast_request = local_props['forecastHourly']
resposne_two = requests.get(local_forecast_request)
json_dict_two = resposne_two.json()
local_forecast_properites = json_dict_two['properties']
hourly_updates = local_forecast_properites['periods']
out = []
for i in hourly_updates:
for key, value in i.items():
if key == "temperature":
out.append(value)
current_weather.set(out[0])
except:
print("Not working.")
#############################################################
class MyWeatherApp:
"""
MyWeatherApp is the primary Frame for this GUI application
"""
def __init__(self, master):
super(MyWeatherApp, self).__init__()
self.master = master
# Create the main window Frame
master_style = ttk.Style()
master_style.configure('Master.TFrame')
self.master.title("My Weather")
self.master.geometry("500x500")
MWA = ttk.Frame(self.master, style='Master.TFrame')
MWA.place(relheight=1.0, relwidth=1.0)
# Run other widgets within this class
MainWeatherHub(MWA)
#############################################################
class MainWeatherHub(MyWeatherApp):
"""
The MainWeatherHub (MWH) is the top panel of the app
"""
def __init__(self, mainwindow):
super(MyWeatherApp, self).__init__()
self.mainwindow = mainwindow
# Create a Frame for the MainWeatherHub
MWH_style = ttk.Style()
MWH_style.configure('MWH.TFrame')
MWH = ttk.Frame(self.mainwindow, style='MWH.TFrame', relief='sunken')
MWH.place(relheight=0.33, relwidth=0.95, relx=0.025, rely=0.025)
# Create an entry widget to take a location
# and store that as a loction variable.
address = StringVar()
loc_entry = ttk.Entry(MWH, textvariable=address)
loc_entry.place(relheight=0.30, relwidth=.95, relx=0.025, rely=0.05)
# Get weather button finds weather for the users location
current_weather = StringVar()
get_weather_button = ttk.Button(loc_entry, text="Get Forecast", command=get_hourly_forecast)
get_weather_button.place(relheight=0.85,relwidth=0.2, relx=0.79, rely=0.075)
#Display weather in the Message widget
weath_display = Message(MWH, textvariable=current_weather)
weath_display.place(relwidth=0.95, relheight=0.55, relx=0.025, rely=0.375)
root = Tk()
my_gui = MyWeatherApp(root)
root.mainloop()
If this script works properly, it should return the current temperature in degrees Fahrenheit of the location that was provided in the entry bar.
You should send it as parameter
def get_hourly_forecast(cur_address):
geocode_url = "...".format(cur_address, API_KEY)
And then assing to button function which runs get_hourly_forecast with string
class MainWeatherHub(MyWeatherApp):
def __init__(self, mainwindow):
self.address = StringVar() # use self.
ttk.Button(loc_entry, text="Get Forecast", command=run_it)
def run_it(self):
get_hourly_forecast(self.address.get())
or using lambda
class MainWeatherHub(MyWeatherApp):
def __init__(self, mainwindow):
ttk.Button(loc_entry, text="Get Forecast", command=lambda:get_hourly_forecast(address.get()))
EDIT:
I see you use current_weather (StringVar from MainWeatherHub) in get_hourly_forecast to set value current_weather.set(out[0]).
You could send current_weather to get_hourly_forecast as parameter
def get_hourly_forecast(cur_address, current_weather):
geocode_url = "...".format(cur_address, API_KEY)
current_weather.set(out[0])
and
class MainWeatherHub(MyWeatherApp):
def __init__(self, mainwindow):
self.address = StringVar() # use self.
self.current_weather = StringVar() # use self.
ttk.Button(loc_entry, text="Get Forecast", command=run_it)
def run_it(self):
get_hourly_forecast(self.address.get(), self.current_weather)
but it could be better to return value from get_hourly_forecast
def get_hourly_forecast(cur_address):
geocode_url = "...".format(cur_address, API_KEY)
return out[0]
and get it in run_it
def run_it(self):
result = get_hourly_forecast(self.address.get())
if result is not None:
self.current_weather.set(result)
This way get_hourly_forecast doesn't work with StringVar and you can use it in other program which doesn't use StringVar.
I created a tkinter GUI, that according to the data entered in it, creates another frame with its own buttons, entries and functions.
Now, I want the user to be able to save this product as a file, and be able to open it when ever it's needed, that has the same buttons and entries that were created.
I have tried filedialog.asksaveasfilename(defaultextension=... ) but it does not work. I have been looking for a filetype for tkinter files. But maybe, because I am new to python I am not seeing the correct path to finding an answer. I will really appreciate if anyone can help me.
Try playing around with the below. It does what I think you need it to:
from tkinter import *
import json
class App:
def __init__(self, root):
self.root = root
self.keys = ["0", "1", "2"]
self.widget = [(Label(self.root), Entry(self.root)), (Label(self.root), Entry(self.root)), (Label(self.root), Entry(self.root))]
self.button = Button(self.root, text="Save", command=self.save)
for i in self.widget:
[1].pack()
for i in self.widget:
i[0].pack()
self.button.pack()
try:
with open("data.json", "r") as f:
self.data = json.load(f)
f.close()
for i in self.keys:
self.widget[int(i)][0].configure(text=self.data[i])
print(self.data)
except FileNotFoundError:
print("File not found")
except KeyError:
print("Keys do not match")
def save(self):
for (i, c) in self.widget:
i.configure(text=c.get())
with open("data.json", "w") as f:
json.dump({self.keys[0]: self.widget[0][1].get(), self.keys[1]: self.widget[1][1].get(), self.keys[2]: self.widget[2][1].get()}, f)
f.close()
root = Tk()
App(root)
root.mainloop()
I have a little situation with Tkinter. I have a piece of code that constantly receives raw EMG data from Thalmic`s Myo Armband and writes that data (plus the name of a gesture) to a csv file. I designed a little tkinter interface to make it look more user-friendly. What I need is to write a function that will stop the previously started recording function.
Also I have a problem with the label, that shows the number of rows in a csv file, but it is another question.
Here is the code:
from gesture_classificator import MyoRaw
import csv
import tkinter
import tkinter.messagebox
import sys
root = tkinter.Tk()
root.title("Recording data")
m = MyoRaw(sys.argv[1] if len(sys.argv) >= 2 else None)
v = tkinter.StringVar()
entry = tkinter.Entry(root, textvariable=v)
entry.grid(row=0, column=0)
v.set("")
def process_emg(emg, times):
name = v.get()
with open('own_test.csv', 'a+') as file:
writing = csv.writer(file)
writing.writerow(emg+(name,))
def show_row_count():
with open('own_test.csv', 'r') as return_me_the_row_count:
reading = csv.reader(return_me_the_row_count)
data = list(reading)
row_count = len(data)
return row_count
def start_recording():
m.add_emg_handler(process_emg)
m.connect()
def stop_recording():
???
B1 = tkinter.Button(root, text="Start the recording", command=start_recording)
B2 = tkinter.Button(root, text="Stop the recording", command=stop_recording)
rows_number = tkinter.Label(root, text=show_row_count)
rows_number.config(text=show_row_count)
B1.grid(row=1, column=0)
B2.grid(row=1, column=1)
rows_number.grid(row=0, column=1)
root.mainloop()
try:
while True:
m.run(1)
except SystemExit:
pass
finally:
m.disconnect()
According to the MyoRaw code, you would probably like the function MyoRaw.disconnect(), which you would use like this:
def stop_recording():
m.disconnect()
In such cases it would be easier and faster for you to check the documentation and/or the code of the framework you are using.
I want to know where and what was changed by user in tkinter's Text widget.
I've found how to get that text was somehow modified by using <<Modified>>event but I can't get actual changes:
from tkinter import *
def reset_modified():
global resetting_modified
resetting_modified = True
text.tk.call(text._w, 'edit', 'modified', 0)
resetting_modified = False
def on_change(ev=None):
if resetting_modified: return
print ("Text now:\n%s" % text.get("1.0", END))
if False: # ????
print ("Deleted [deleted substring] from row %d col %d")
if False: # ????
print ("Inserted [inserted substring] at row %d col %d")
reset_modified()
resetting_modified = False
root = Tk()
text = Text(root)
text.insert(END, "Hello\nworld")
text.pack()
text.bind("<<Modified>>", on_change)
reset_modified()
root.mainloop()
For example, if I select 'ello' part from "hello\nworld" in Text widget then I press 'E', then I want to see
"Deleted [ello] from row 0 col 1" followed by "Inserted [E] at row 0 col 1"
is it possible to get such changes (or at least their coordinates) or I have basically to diff text on each keystroke if I want to detect changes run time?
Catching the low level inserts and deletes performed by the underlying tcl/tk code is the only good way to do what you want. You can use something like WidgetRedirector or you can do your own solution if you want more control.
Writing your own proxy command to catch all internal commands is quite simple, and takes just a few lines of code. Here's an example of a custom Text widget that prints out every internal command as it happens:
from __future__ import print_function
import Tkinter as tk
class CustomText(tk.Text):
def __init__(self, *args, **kwargs):
"""A text widget that report on internal widget commands"""
tk.Text.__init__(self, *args, **kwargs)
self._orig = self._w + "_orig"
self.tk.call("rename", self._w, self._orig)
self.tk.createcommand(self._w, self.proxy)
def proxy(self, command, *args):
# this lets' tkinter handle the command as usual
cmd = (self._orig, command) + args
result = self.tk.call(cmd)
# here we just echo the command and result
print(command, args, "=>", result)
# Note: returning the result of the original command
# is critically important!
return result
if __name__ == "__main__":
root = tk.Tk()
CustomText(root).pack(fill="both", expand=True)
root.mainloop()
After digging around, I've found that idlelib has WidgetRedirector which can redirect on inserted/deleted events:
from tkinter import *
from idlelib.WidgetRedirector import WidgetRedirector
def on_insert(*args):
print ("INS:", text.index(args[0]))
old_insert(*args)
def on_delete(*args):
print ("DEL:", list(map(text.index, args)))
old_delete(*args)
root = Tk()
text = Text(root)
text.insert(END, "Hello\nworld")
text.pack()
redir = WidgetRedirector(text)
old_insert=redir.register("insert", on_insert)
old_delete=redir.register("delete", on_delete)
root.mainloop()
Though it seems hacky. Is there a more natural way?