I have just started utilizing Python's tkinter module to create some basic GUIs. In the GUI shown below, the user is prompted to select an oil index and subsequent pricing information will appear (the price information is web scraped). However, I have not found a convenient way to clear the pricing label text for when the user selects another oil index. I have the full code attached below. Any suggestions would be greatly appreciated. Thank you.
# Import Python Modules
from tkinter import *
from ttk import *
import urllib2
from bs4 import BeautifulSoup
import re
# Generate Basic Window
root = Tk()
root.geometry("225x125")
root.resizable(0,0)
root.title("Global Oil Price GUI")
# Functions
def fetchdata(event):
index = combo.current() # Get index of combobox selection
# Obtain HTML
url = 'http://oilprice.com/oil-price-charts/45' # URL to be scraped
content = urllib2.urlopen(url)
parsed = BeautifulSoup(content,'html.parser')
# Parse HTML
oilprice = parsed.findAll('td',attrs = {'class': 'last_price'})
change = parsed.findAll('td',{'class':['change_up flat_change_cell','change_down flat_change_cell','change_up','change_down']})
change_percent = parsed.findAll('td',{'class':['change_up_percent percent_change_cell','change_down_percent percent_change_cell','change_up_percent','change_down_percent']})
# Pre-Initialize Arrays
oilprice_extract = []
change_extract = []
change_percent_extract = []
time_extract = []
# Loop and Extract Text
for ele_price, ele_change, ele_change_percent in zip(oilprice,change,change_percent):
oilprice_extract.append(float(ele_price.text))
change_extract.append(ele_change.text)
change_percent_extract.append(ele_change_percent.text.split('%')[0] + '%')
time_extract.append(re.sub('\n\t',' ',ele_change_percent.text.split('%')[1]))
# Fill Field Based Upon Selection
price_label = Label(root,text = oilprice_extract[index]).grid(row = 2,column = 2)
change_label = Label(root,text = change_extract[index]).grid(row = 3,column = 2)
change_percent_label = Label(root,text = change_percent_extract[index]).grid(row = 4,column = 2)
update_label = Label(root,text = time_extract[index]).grid(row = 5,column = 2)
# Driver Code
combo_label = Label(root,text = "Futures & Indexes",justify = LEFT).grid(row = 0, column = 0)
combo = Combobox(root,values = ["WTI Crude","Brent Crude","Mars US","OPEC Basket","Canadian Crude Index"],width = 17)
combo.grid(row = 1, column = 0)
combo.bind("<<ComboboxSelected>>",fetchdata)
price_display = Label(root,text = " Price (USD):").grid(row = 2,column = 0)
change_display = Label(root,text = "Change:").grid(row = 3,column = 0)
change_percent_display = Label(root,text = "Change Percent:").grid(row = 4,column = 0)
update_display = Label(root,text = "Last Updated:").grid(row = 5,column = 0)
root.mainloop() # Run window continuously**
Update:
Still a slight problem.
Scenario: User selects WTI Crude as first choice which shows: 'Last Update: (11 Minutes Delay)'
User then selects Mars US which should show something like 'Last Update: (2 Days Delay)'
Problem: The labels overlap each other as shown in this photo EXAMPLE PHOTO
Any solution to this?
The correct way is to use a StringVar to set the initial value of the Label, then you just need to call the .set() method of the StringVar instance you want to update.
Example:
price_str = StringVar()
prica_label = Label(root, textvariable=price_str).pack()
price_str.set("new price")
Clearing Label Text:
as jasonharper said. Use label.config(text="something")
The following script shows an example, where a label is dynamically incremented by 1 until the stop button is pressed:
import tkinter as tk
counter = 0
def counter_label(label):
def count():
global counter
counter += 1
label.config(text=str(counter))
label.after(1000, count)
count()
root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()
reference: https://www.python-course.eu/tkinter_labels.php
labels overlap:
you shouldn't recreate label over and over again.
Besides, I think the following example will be better.
from tkinter import *
from tkinter.ttk import *
import requests
from tkinter.ttk import Combobox
from bs4 import BeautifulSoup, SoupStrainer
# import re # As long as you can make do with str.replace(), you should use it instead of re.sub.
class CQueryOil(Tk):
def __init__(self, query_country: list):
super().__init__() # init Tk
self.__url = 'http://oilprice.com/oil-price-charts/45'
self._query_country = query_country
self._intvar_price = IntVar()
self._strvar_change = StringVar(value='')
self._strvar_change_percent = StringVar(value='')
self._strvar_update_time = StringVar(value='')
self.init_ui()
#property
def url(self):
return self.__url
#property
def query_list(self):
return self._query_country
def run(self):
self.mainloop()
def init_ui(self) -> None:
self.geometry("225x125")
self.resizable(0, 0)
self.title("Global Oil Price GUI")
[self.grid_columnconfigure(col, weight=1) for col in (1, 2)]
n_padx = 5
Label(self, text="Futures & Indexes", justify=LEFT).grid(row=0, column=0, padx=n_padx, sticky='w')
combo = Combobox(self, values=self.query_list, width=17)
combo.grid(row=1, column=0, padx=n_padx, columnspan=2, sticky='w')
combo.bind("<<ComboboxSelected>>", lambda event: self.update(event, combo=combo))
for cur_row, label_name in enumerate(['Price (USD):', 'Change:', 'Change Percent:', 'Last Updated:']):
Label(self, text=label_name, width=14).grid(row=2 + cur_row, column=0, padx=n_padx, sticky='e')
Label(self, textvariable=self._intvar_price).grid(row=2, column=1, sticky='w')
Label(self, textvariable=self._strvar_change).grid(row=3, column=1, sticky='w')
Label(self, textvariable=self._strvar_change_percent).grid(row=4, column=1, sticky='w')
Label(self, textvariable=self._strvar_update_time).grid(row=5, column=1, sticky='w')
def update(self, event, combo) -> None:
resp = requests.get(self.url)
if resp.status_code != 200:
return
filter_data = SoupStrainer('tr', attrs={'class': ['stripe show_graph', 'stripe show_graph update_on_load']
# 'data-id': ['45', '46', '50', '29', '68']
})
parsed = BeautifulSoup(resp.text, 'lxml', parse_only=filter_data)
idx = combo.current() # Get index of combobox selection
try:
dst_td_tags = parsed.find('td', string=self.query_list[idx]).find_next_siblings()
except:
import traceback
print(traceback.format_exc())
raise NameError(f'====Must match the data on the web page. Name:{self.query_list[idx]}=====') # literal format Py3.6↑
dst_list = [td.text for td in dst_td_tags]
price, change, change_percent, update_time = dst_list
change_percent = change_percent.split('%')[0] # As long as you can make do with str.replace(), you should use it instead of re.sub.
update_time = update_time.replace('\n\t', ' ')
change_percent = change_percent
update_time = update_time
self._intvar_price.set(price)
self._strvar_change.set(change)
self._strvar_change_percent.set(change_percent)
self._strvar_update_time.set(update_time)
if __name__ == '__main__':
obj = CQueryOil(["WTI Crude", "Brent Crude", "Mars US", "Opec Basket", "Canadian Crude Index"]) # Must match the data on the web page
obj.run()
Related
I want the code to get the last price and use it to divide the entered quantity (qty = "entered quantity" / "last price"). Finally, use the quantity to open a short or long order.I have a search bar and an input field for quantity. From the search bar, I can select all the USDT pairs available in Binance Futures. Currently #deneme field gets last price too but it's not working in the end.
from tkinter import *
from operator import truediv
import os
import tkinter
from pickle import TRUE
from tkinter import ttk
from tkinter import messagebox
from tkinter.messagebox import showinfo
from binance.client import Client
####API KEYS
api_key = os.environ.get('binance_api')
api_secret = os.environ.get('binance_secret')
client = Client(api_key, api_secret)
#Ekran
root= Tk()
root.geometry('300x300')
l = Label(root, text="MARKET ORDER")
l.config(font=("MARKET ORDER", 25))
l.pack()
#Bar
l = Label(root, text="Coin Girin")
l.config(font=("Coin Girin", 10))
l.pack()
lst = exchange_info = client.futures_exchange_info()
usdt_pairs = [s['symbol'] for s in exchange_info['symbols'] if 'USDT' in s['symbol']]
print(usdt_pairs)
def search(event):
value = event.widget.get()
if value == '':
combo_box['values'] = usdt_pairs
else:
data = []
for item in usdt_pairs:
if value.lower() in item.lower():
data.append(item)
combo_box['values'] = data
combo_box = ttk.Combobox(root,value=usdt_pairs)
combo_box.set('')
combo_box.pack()
combo_box.bind('<KeyRelease>', search)
#deneme
def show_ticker_info(event=None):
selected_symbol = combo_box.get()
ticker_info = client.futures_ticker(symbol=selected_symbol,timeframe='1m')
ticker_text.config(text=ticker_info['lastPrice'])
root.after(100, show_ticker_info) # update price every 100 milliseconds
ticker_text = Label(root, text="")
ticker_text.pack()
combo_box.bind("<<ComboboxSelected>>", show_ticker_info)
root.after(0, show_ticker_info) # start updating immediately
#qty girme
l = Label(root, text="Miktar Girin")
l.config(font=("Miktar Girin", 10))
l.pack()
qty_entry = Entry(root)
qty_entry.pack()
#Buton SAT
def buttonFunction():
qty = qty_entry.get()
selected_symbol = combo_box.get()
order = client.futures_create_order(symbol=selected_symbol,
side=Client.SIDE_SELL,
type=Client.ORDER_TYPE_MARKET,
leverage=20,
quantity=qty)
if order:
global pop
pop = Toplevel(root)
pop.title("SELL")
pop.geometry("250x150")
pop.config(bg="green")
pop_label = Label(pop, text="ORDER PLACED", bg="black", fg="white")
pop_label.pack(pady=10)
b = Button(root, text="SAT", bg="red", fg="white", command=buttonFunction)
b.config(font=("bas", 18))
b.pack(side=LEFT)
#Buton AL
def buttonFunction2():
selected_symbol = combo_box.get()
qty = qty_entry.get()
order = client.futures_create_order(symbol=selected_symbol,
side=Client.SIDE_BUY,
type=Client.ORDER_TYPE_MARKET,
leverage=20,
quantity=qty)
if order:
global pop
pop = Toplevel(root)
pop.title("BUY")
pop.geometry("250x150")
pop.config(bg="green")
pop_label = Label(pop, text="ORDER PLACED", bg="black", fg="white")
pop_label.pack(pady=10)
b2 = Button(root, text="AL", bg="green", fg="white", command=buttonFunction2,)
b2.config(font=("bas", 18))
b2.pack(side=RIGHT)
root.mainloop()
I cannot test your code. You can modify my example.
Snippet:
import locale
amount = 125000
# set locale to US
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
# format US currency value
US_dollar = locale.currency(amount, grouping=True)
print(US_dollar)
Result: $125,000.00
I am losing my peanuts here. I am trying to clear two label values but i get an error
AttributeError: 'Label' object has no attribute 'delete'
basically if i were to click the calculate subtotal button then click the divide total button. I get my intended values. Now if I were to click on the clear values button i get an error. Literally shaking my head as I type this. Anyone care to explain why this is the case?
try:
import Tkinter as tk
except:
import tkinter as tk
class GetInterfaceValues():
def __init__(self):
self.root = tk.Tk()
self.totalValue = tk.StringVar()
self.root.geometry('500x200')
self.calculateButton = tk.Button(self.root,
text='Calculate Subtotal',
command=self.getSubtotals)
self.divideTotalButton = tk.Button(self.root,
text='Divide total',
command=self.divide)
self.textInputBox = tk.Text(self.root, relief=tk.RIDGE, height=1, width = 6, borderwidth=2)
self.firstLabel = tk.Label(self.root, text="This is the subtotal:")
self.secondLabel = tk.Label(self.root, text="This is the Divide Total:")
self.clearTotalButton = tk.Button(self.root, text='clear the values',command = self.clear)
self.firstLabel.pack(side="bottom")
self.secondLabel.pack(side="bottom")
self.textInputBox.pack()
self.calculateButton.pack()
self.divideTotalButton.pack()
self.clearTotalButton.pack()
self.root.mainloop()
def getTextInput(self):
result = self.textInputBox.get("1.0", "end")
return result
def getSubtotals(self):
userValue = int(self.getTextInput())
self.firstLabel["text"] = self.firstLabel["text"] + str(userValue * 5)
def divide(self):
userValue = int(self.getTextInput())
self.secondLabel["text"] = self.secondLabel["text"] + str(userValue / 10)
def clear(self):
self.firstLabel["text"] = self.firstLabel.delete("1.0","end")
app = GetInterfaceValues()
try:
import Tkinter as tk
except:
import tkinter as tk
class GetInterfaceValues():
def __init__(self):
self.root = tk.Tk()
self.totalValue = tk.StringVar()
self.root.geometry('500x200')
self.calculateButton = tk.Button(self.root,
text='Calculate Subtotal',
command=self.getSubtotals)
self.divideTotalButton = tk.Button(self.root,
text='Divide total',
command=self.divide)
self.textInputBox = tk.Text(self.root, relief=tk.RIDGE, height=1, width = 6, borderwidth=2)
self.firstLabelDefault = "This is the subtotal:"
self.secondLabelDefault = "This is the Divide Total:"
self.firstLabel = tk.Label(self.root, text=self.firstLabelDefault)
self.secondLabel = tk.Label(self.root, text=self.secondLabelDefault)
self.clearTotalButton = tk.Button(self.root, text='clear the values',command = self.clear)
self.firstLabel.pack(side="bottom")
self.secondLabel.pack(side="bottom")
self.textInputBox.pack()
self.calculateButton.pack()
self.divideTotalButton.pack()
self.clearTotalButton.pack()
self.root.mainloop()
def getTextInput(self):
result = self.textInputBox.get("1.0", "end")
return result
def getSubtotals(self):
userValue = int(self.getTextInput())
self.firstLabel["text"] = self.firstLabel["text"] + str(userValue * 5)
def divide(self):
userValue = int(self.getTextInput())
self.secondLabel["text"] = self.secondLabel["text"] + str(userValue / 10)
def clear(self):
self.firstLabel["text"] = self.firstLabelDefault
self.secondLabel["text"] = self.secondLabelDefault
self.textInputBox.delete("1.0", "end")
app = GetInterfaceValues()
You may have confused the methods of tkinter.Text and tkinter.Label. The method you called was tkinter.label.delete, which is not defined (does not exist), however it does exist for the tkinter.Text. Therefore, the only way to 'reset' would be to change the text attribute of the tkinter.Labels back to a 'default' string. It would perhaps be more appropriate to use another widget instead.
I've created a temperature converter programme in which the calculated temperature from an entry widget gets displayed in a separate label, what I need to do is to grab that converted variable and put it into a list.
I think that making a connected entry widget to the label widget would work where they are connected so I could grab the variable using the .get method but that would look awfully messy. Is there any other way I could proceed with this?
This is my first post and I am a beginner in Python, very sorry if the code looks messy and if I included too much code.
data = []
tempVal = "Celcius"
def store_temp(sel_temp):
global tempVal
tempVal = sel_temp
class Calculator:
def __init__(self, num_a, num_b):
self.num_a= num_a
self.num_b = num_b
def convert(self):
if tempVal == 'Fahrenheit':
return float((float(self.num_a) - 32)* 5 / 9)
if tempVal == 'Celcius':
return float((float(self.num_a) * 9/ 5) + 32)
def display_add(entry_numa,entry_numb,label_answer):
#get the value from entry_numa
num_a = entry_numa.get()
num_b = entry_numb.get()
num_a = str(num_a)
num_b = str(num_b)
#create an object
global data
calc = Calculator(num_a,num_b)
label_answer['text'] = calc.convert()
data += [calc]
def calc_history():
global data
#creat e another window
window_calc_list = Tk()
window_calc_list.geometry("400x200")
#create a listbox
listbox_calc_list = Listbox(window_calc_list, width= 300)
listbox_calc_list.pack()
listbox_calc_list.insert(END, "list of data")
for info in data:
listbox_calc_list.insert(END, str(info.num_a) + " " + str(info.num_b) + " " )
window_calc_list.mainloop()
def main():
window = Tk()
window.geometry("500x150")
validate_letter = window.register(only_letters)
validate_nb = window.register(only_numbers_max_3)
label = Label(window, width = 30, background = 'lightblue', text='enter temperature, only numbers')
label.grid(row=0, column=0)
entry_numa = Entry(window, width = 30, validate="key", validatecommand=(validate_nb, '%d', '%P'))
entry_numa.grid(row = 0, column = 1)
#create another label and entry object for num_b
label_numb = Label(window, width = 30, background = 'lightblue', text='enter location, only letters')
label_numb.grid(row=1, column=0)
entry_numb = Entry(window, width = 30, validate="key", validatecommand=(validate_letter, '%d', '%S'))
entry_numb.grid(row = 1, column = 1)
#create another label to display answer
label_answer = Label(window, width = 30, background = 'lightyellow')
label_answer.grid(row = 2, column = 1)
entry_answer = Entry(window, width = 30)
entry_answer.grid(row = 2, column = 0)
button_add = Button(window, text = "ADD", command = lambda: display_add(entry_numa,entry_numb,label_answer))
button_add.grid(row=3, column = 0)
button_delete = Button(window, text = "DELETE", command = lambda: delete_data(data))
button_delete.grid(row=3, column = 2)
#create another button to display all previous calculations
button_display = Button(window,text = "calc_history", command = lambda: calc_history())
button_display.grid(row=3, column = 1)
var = StringVar()
dropDownList = ["Celcius", "Fahrenheit"]
dropdown = OptionMenu(window, var,dropDownList[0], *dropDownList, command=store_temp)
dropdown.grid(row=0, column=2)
window.mainloop()
A tk.Label displayed value can be accessed via the text property
, labelwidgetname['text'].
Depeneding on when and how you want the independent list of stored values
to be updated there are a variety of options. The example shows one if the
user is required to press a submission button. This could be adapted,
for example,when the tempreture calculation is performed.
Of course it would be simpler to update the list of stored values directly at the point in the script where the calculated tempreture for the label text has been derived.
import tkinter as tk
stored_values = []
def add_labelvalue_tolist(temp):
'''Store label value to list.'''
stored_values.append(temp)
print('contents of list', stored_values)
def add_entry_tolabel(event):
display_label['text'] = user_entry.get()
ROOT = tk.Tk()
user_entry = tk.Entry()
user_entry.grid(column=0, row=0)
user_entry.bind('<KeyRelease>', add_entry_tolabel)
display_label = tk.Label()
display_label.grid(column=1, row=0)
# update list via button command linked to label text value
add_button = \
tk.Button(text='add to list',
command=lambda:add_labelvalue_tolist(display_label['text']))
add_button.grid(column=0, row=1)
ROOT.mainloop()
try making a function that is like this
def letterused():
converter=(letter.get())# letter is a entry box at the bottom is the code
converted.set(converter)
for i in range(1):
used_letters1.append(converter) #list
letter = ttk.Entry(root, width = 20,textvariable = letter)
letter.pack()
Trying to print the reviews array as a list to my label so it doesn't just come out in a single line.
import pandas as pd
import numpy as np
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showwarning, showinfo
movies = pd.read_csv('C:/Users/Admin/Python Programs/ml-latest-small/movies.csv')
ratings = pd.read_csv('C:/Users/Admin/Python Programs/ml-latest-small/ratings.csv')
ratings.drop(['timestamp'], axis=1, inplace= True)
class App(Frame):
def replace_name(x):
return movies[movies['movieId']==x].title.values[0]
ratings.movieId = ratings.movieId.map(replace_name)
M = ratings.pivot_table(index=['userId'], columns=['movieId'], values='rating')
def pearsons(s1, s2):
s1_c = s1 - s1.mean()
s2_c = s2 - s2.mean()
return np.sum(s1_c * s2_c) / np.sqrt(np.sum(s1_c ** 2) * np.sum(s2_c ** 2))
def get_recs(self):
movie_name = self.mn.get()
num_recs_str = self.nr.get()
num_recs = int(num_recs_str)
reviews = []
for title in App.M.columns:
if title==movie_name:
continue
cor = App.pearsons(App.M[movie_name], App.M[title])
if np.isnan(cor):
continue
else:
reviews.append((title, cor))
reviews.sort(key=lambda tup: tup[1], reverse=True)
for x in reviews:
self.label3.config(text= "\n" + str(reviews[:num_recs]))
#self.label3.config(text=reviews[:num_recs])
return reviews[:num_recs]
def __init__(self, master):
Frame.__init__(self, master)
self.filename = None
label1=Label(master, text="Movie: ").grid(row=0)
label2=Label(master, text="Recommendations: ").grid(row=1)
self.label3=Label(master, text = "", font = 'Purisa', fg='blue')
self.label3.grid(row = 3)
self.mn = Entry(master)
self.mn.grid(row = 0, column = 1)
#self.mn.delete(0, END)
self.mn.insert(0, "Enter Movie Name")
self.nr = Entry(master)
self.nr.grid(row = 1, column = 1)
#self.nr.delete(0, END)
self.nr.insert(0, "Enter Number of Recommendations")
button1 = Button(self, text="Start", command=self.get_recs)
button2 = Button(self, text="Exit", command=master.destroy)
button1.grid(row = 2, padx= 5)
button2.grid(row = 2, column = 1, padx = 5)
self.grid()
root = Tk()
root.title("Recommender")
root.geometry("500x500")
app = App(root)
root.mainloop()
Here is an image of the current output
I couldn't modify your code because I don't have the files you opened in your code. However, this is an idea to solve your question:
from tkinter import *
things_to_print=['something','one thing','another']
root=Tk()
for i in range(len(things_to_print)):
exec('Label%d=Label(root,text="%s")\nLabel%d.pack()' % (i,things_to_print[i],i))
root.mainloop()
I think you can solve your problem by substituting your reviews into my things_to_print and maybe some other slight modifications.
Basically I want there to be a list, which displays files I have stored in a certain folder, and beside the list there are buttons which open up separate windows which can edit or add a new item to that list.
I want addchar to open up an new window with spaces for different fields, then when you press a "create" button in that window it closes, creates a file on the info you just entered (that's why i've imported os) as well as creating a new item on the main interface's listbox as the name of the character (which is one of the fields). The removechar function would remove that entry and delete the file, and editchar would open up a window similar to addchar, but with the info of the selected item on the list.
EDIT: Here's the code so far
from tkinter import *
import os
import easygui as eg
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
# character box
Label(frame, text = "Characters Editor").grid(row = 0, column = 0, rowspan = 1, columnspan = 2)
charbox = Listbox(frame)
for chars in []:
charbox.insert(END, chars)
charbox.grid(row = 1, column = 0, rowspan = 5)
charadd = Button(frame, text = " Add ", command = self.addchar).grid(row = 1, column = 1)
charremove = Button(frame, text = "Remove", command = self.removechar).grid(row = 2, column = 1)
charedit = Button(frame, text = " Edit ", command = self.editchar).grid(row = 3, column = 1)
def addchar(self):
print("not implemented yet")
def removechar(self):
print("not implemented yet")
def editchar(self):
print("not implemented yet")
root = Tk()
root.wm_title("IA Development Kit")
app = App(root)
root.mainloop()
Ok, I implemented addchar and removechar for you (and tweaked a few other things in your code). I'll leave the implementation of editchar to you - take a look at what I wrote to help you, as well as the listbox documentation
from Tkinter import * # AFAIK Tkinter is always capitalized
#import os
#import easygui as eg
class App:
characterPrefix = "character_"
def __init__(self, master):
self.master = master # You'll want to keep a reference to your root window
frame = Frame(master)
frame.pack()
# character box
Label(frame, text = "Characters Editor").grid(row = 0, column = 0, rowspan = 1, columnspan = 2)
self.charbox = Listbox(frame) # You'll want to keep this reference as an attribute of the class too.
for chars in []:
self.charbox.insert(END, chars)
self.charbox.grid(row = 1, column = 0, rowspan = 5)
charadd = Button(frame, text = " Add ", command = self.addchar).grid(row = 1, column = 1)
charremove = Button(frame, text = "Remove", command = self.removechar).grid(row = 2, column = 1)
charedit = Button(frame, text = " Edit ", command = self.editchar).grid(row = 3, column = 1)
def addchar(self, initialCharacter='', initialInfo=''):
t = Toplevel(root) # Creates a new window
t.title("Add character")
characterLabel = Label(t, text="Character name:")
characterEntry = Entry(t)
characterEntry.insert(0, initialCharacter)
infoLabel = Label(t, text="Info:")
infoEntry = Entry(t)
infoEntry.insert(0, initialInfo)
def create():
characterName = characterEntry.get()
self.charbox.insert(END, characterName)
with open(app.characterPrefix + characterName, 'w') as f:
f.write(infoEntry.get())
t.destroy()
createButton = Button(t, text="Create", command=create)
cancelButton = Button(t, text="Cancel", command=t.destroy)
characterLabel.grid(row=0, column=0)
infoLabel.grid(row=0, column=1)
characterEntry.grid(row=1, column=0)
infoEntry.grid(row=1, column=1)
createButton.grid(row=2, column=0)
cancelButton.grid(row=2, column=1)
def removechar(self):
for index in self.charbox.curselection():
item = self.charbox.get(int(index))
self.charbox.delete(int(index))
try:
os.remove(characterPrefix + item)
except IOError:
print "Could not delete file", characterPrefix + item
def editchar(self):
# You can implement this one ;)
root = Tk()
root.wm_title("IA Development Kit")
app = App(root)
root.mainloop()