How can ı get last price and convert coin curreny to usdt - python

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

Related

Variables not updating with Entry

Once again I am here asking for guidance with my crypto trading bot. This time, I am trying to update variables using Tkinter Entries. The default value for the Entry that I am trying to update is Crypto Symbol. I am trying to get a variable sym from this to use with the Binance API. I need to do sym = crypto.get()+'USDT' to get the variable that I need to plug into the command for the Trade button. For testing purposes, I set the command to print(sym) because I am trying to get it to update and that makes it easy to see what is going on. When I press the button, no matter what I have entered in the Entry, it always spits out Crypto SymboUSDT because Crypto Symbol is the original value, showing that what I am entering doesn't change anything. I will attach my code below, if you have a potential fix, please let me know :)
import pandas as pd
from pandas.core import frame, indexing
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import tkinter as tk
from tkinter import *
from tkinter.ttk import *
from tkinter import Entry, Tk, filedialog, Text
root = tk.Tk()
root.geometry('500x250')
root.title('Binance Bot')
# API Key Information
api_key = 'Censored'
api__secret = 'Censored'
# Entries
#Crypto Symbol
crypto = Entry(root, width=20, borderwidth=2, fg='gray')
crypto.insert(0, "Crypto Symbol")
def cryptoFocusIn(event):
crypto.config(foreground='black')
if crypto.get() == 'Crypto Symbol':
crypto.config(foreground='black')
crypto.delete(0, END)
def cryptoFocusOut(event):
if crypto.get() == '':
crypto.delete(0, END)
crypto.config(foreground='gray')
crypto.insert(0, 'Crypto Symbol')
crypto.bind('<FocusIn>', cryptoFocusIn)
crypto.bind('<FocusOut>', cryptoFocusOut)
crypto.pack()
sym = crypto.get()+'USDT'
# Order amount
OrderAmt = Entry(root, width=20, borderwidth=2, fg='gray')
OrderAmt.insert(0, "Order Amount (Coins)")
def AmtFocusIn(event):
OrderAmt.config(foreground='black')
if OrderAmt.get() == 'Order Amount (Coins)':
OrderAmt.config(foreground='black')
OrderAmt.delete(0, END)
def AmtFocusOut(event):
if OrderAmt.get() == '':
OrderAmt.delete(0, END)
OrderAmt.config(foreground='gray')
OrderAmt.insert(0, 'Order Amount (Coins)')
OrderAmt.bind('<FocusIn>', AmtFocusIn)
OrderAmt.bind('<FocusOut>', AmtFocusOut)
OrderAmt.pack()
qty = OrderAmt.get()
#Percentage drop for bot to buy
PercentDrop = Entry(root, width=20, borderwidth=2, fg='gray')
PercentDrop.insert(0, "% Drop to Buy")
def PDFocusIn(event):
PercentDrop.config(foreground='black')
if PercentDrop.get() == '% Drop to Buy':
PercentDrop.config(foreground='black')
PercentDrop.delete(0, END)
def PDFocusOut(event):
if PercentDrop.get() == '':
PercentDrop.delete(0, END)
PercentDrop.config(foreground='gray')
PercentDrop.insert(0, '% Drop to Buy')
PercentDrop.bind('<FocusIn>', PDFocusIn)
PercentDrop.bind('<FocusOut>', PDFocusOut)
PercentDrop.pack()
#Percent gain to Sell
PercentRaise = Entry(root, width=20, borderwidth=2, fg='gray')
PercentRaise.insert(0, "% Raise to Sell")
def PRFocusIn(event):
PercentRaise.config(foreground='black')
if PercentRaise.get() == '% Raise to Sell':
PercentRaise.config(foreground='black')
PercentRaise.delete(0, END)
def PRFocusOut(event):
if PercentRaise.get() == '':
PercentRaise.delete(0, END)
PercentRaise.config(foreground='gray')
PercentRaise.insert(0, '% Raise to Sell')
PercentRaise.bind('<FocusIn>', PRFocusIn)
PercentRaise.bind('<FocusOut>', PRFocusOut)
PercentRaise.pack()
# Percent bottom out to sell - Failsafe to not lose money
PercentBottom = Entry(root, width=20, borderwidth=2, fg='gray')
PercentBottom.insert(0, "% Drop Failsafe")
def PBFocusIn(event):
PercentBottom.config(foreground='black')
if PercentBottom.get() == '% Drop Failsafe':
PercentBottom.config(foreground='black')
PercentBottom.delete(0, END)
def PBFocusOut(event):
if PercentBottom.get() == '':
PercentBottom.delete(0, END)
PercentBottom.config(foreground='gray')
PercentBottom.insert(0, '% Drop Failsafe')
PercentBottom.bind('<FocusIn>', PBFocusIn)
PercentBottom.bind('<FocusOut>', PBFocusOut)
PercentBottom.pack()
# Get account information
client = Client(api_key, api__secret, tld='us')
#print(client.get_account())
# Datastream via websocket
def getMinuteData(symbol, interval, lookback):
frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+' min ago EST'))
frame = frame.iloc[:, :6]
frame.columns = ['Time', 'Open', 'High', 'Low', 'Close', 'Volume']
frame = frame.set_index('Time')
frame.index = pd.to_datetime(frame.index, unit='ms')
frame = frame.astype(float)
return frame
test = getMinuteData('BTCUSDT', '1m', '30')
# Trading Strategy - Buy if asset fell by more than 0.2% withint the last 30 min
# Sell if asset rises by more than 0.15% or falls further by 0.15%
def strategyTest(symbol, qty, entered=False):
df = getMinuteData(symbol, '1m', '30')
cumulRet = (df.Open.pct_change() + 1).cumprod() -1
if not entered:
if cumulRet [-1] < -0.002:
order = client.create_order(symbol=symbol, side='BUY', type = 'MARKET', quantity=qty)
print(order)
entered = True
else:
print("No trade executed")
if entered:
while True:
df = getMinuteData(symbol, '1m', '30')
sinceBuy = df.loc[df.index > pd.to_datetime(order['transactTime'], unit='ms')]
if len(sinceBuy) > 0:
sinceBuyReturns = (sinceBuy.Open.pct_change() + 1).cumprod() -1
if sinceBuyReturns[-1] > 0.0015 or sinceBuyReturns[-1] < -0.0015:
order = client.create_order(symbol=symbol, side='SELL', type = 'MARKET', quantity=qty)
print(order)
break
def confirm():
sym = crypto.get()+'USDT'
qty = OrderAmt.get()
# Buttons
Confirm = tk.Button(root, text='Confirm?', padx=10, pady=5, fg = 'white', bg = 'black', command = lambda: confirm() )
Confirm.pack()
#Trade = tk.Button(root, text='Trade', padx=10, pady=10, fg='white', bg='black', command = lambda: strategyTest(sym, qty) )
Trade = tk.Button(root, text='Trade', padx=10, pady=5, fg='white', bg='black', command = lambda: print(sym) )
Trade.pack()
root.mainloop()```

Python tkinter Clearing Label Text

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()

How to clear a label using tkinter when pressing a button?

I am using labels to show a generated password in my tkinter password generator program, but when I change the length of a password from a lower value than before (for example from a length of 20 to 10) the label displaying the password appears to be overwritten - it does not clear. I have searched methods to do this, but I cannot seem to find any.
Here is my code:
from tkinter import *
from random import *
import string
root = Tk()
root.wm_title("Password Generator")
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
root.geometry("1000x1000")
title = Label(topFrame, text="Length", fg="blue")
title.grid(row=3,column=5)
var = DoubleVar()
Slider_1 = Scale(root,orient=HORIZONTAL,length=32*10,from_=0,to=32, variable
= var)
Slider_1.pack()
passLen = var.get()
uppercaseLetters = "QWERTYUIOPASDFGHJKLZXCVBNM"
lowercaseLetters = "qwertyuiopasdfghjklzxcvbnm"
symbols = "!£$%^&*()_+-=}{][~##':;?>/.<,"
digits = "1234567890"
def gen():
characters = uppercaseLetters + lowercaseLetters + symbols + digits
password = "".join(choice(characters) for x in range(int(var.get())))
passLabel = Label(topFrame, text=password)
passLabel.grid(row=4, column=5)
genButton = Button(topFrame, text="Generate Password", fg="blue",
command=gen)
genButton.grid(row=1, column=5)
root.mainloop()
When I set the length to 32 characters:
And when I set the length to 6 characters it does not clear the old password label - it simply overwrites it in the middle of the old password label:
First of all, move your gen method definition to just below imports so that they're recognized in the main body. Then take your widgets and mainloop out of the method. Just configure passLabel's text when needed:
def gen():
characters = uppercaseLetters + lowercaseLetters + symbols + digits
password = "".join(choice(characters) for x in range(int(var.get())))
passLabel['text'] = password
Entire code with suggested edits been made:
from tkinter import *
from random import *
import string
def gen():
characters = uppercaseLetters + lowercaseLetters + symbols + digits
password = "".join(choice(characters) for x in range(int(var.get())))
passLabel['text'] = password
root = Tk()
root.wm_title("Password Generator")
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
root.geometry("1000x1000")
title = Label(topFrame, text="Length", fg="blue")
title.grid(row=3,column=5)
var = DoubleVar()
Slider_1 = Scale(root,orient=HORIZONTAL,length=32*10,from_=0,to=32, variable
= var)
Slider_1.pack()
passLen = var.get()
uppercaseLetters = "QWERTYUIOPASDFGHJKLZXCVBNM"
lowercaseLetters = "qwertyuiopasdfghjklzxcvbnm"
symbols = "!£$%^&*()_+-=}{][~##':;?>/.<,"
digits = "1234567890"
passLabel = Label(topFrame)
passLabel.grid(row=4, column=5)
genButton = Button(topFrame, text="Generate Password", fg="blue",
command=gen)
genButton.grid(row=1, column=5)
root.mainloop()
Change two things:
First:
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
passLabel = Label(topFrame)
root.geometry("1000x1000")
Second:
def gen():
characters = uppercaseLetters + lowercaseLetters + symbols + digits
password = "".join(choice(characters) for x in range(int(var.get())))
passLabel.config(text=password)
passLabel.grid(row=4, column=5)
"How to clear a label using tkinter when pressing a button?"
Below is an example that clears label's text when the button is pressed:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def clear_widget_text(widget):
widget['text'] = ""
if __name__ == '__main__':
root = tk.Tk()
label = tk.Label(root, text="This will be cleared.")
button = tk.Button(root, text="Clear",
command=lambda : clear_widget_text(label))
label.pack()
button.pack()
root.mainloop()
Below is an example that destroys label when button is pressed:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def clear_widget(widget):
widget.destroy()
if __name__ == '__main__':
root = tk.Tk()
label = tk.Label(root, text="This will be cleared.")
button = tk.Button(root, text="Clear",
command=lambda : clear_widget(label))
label.pack()
button.pack()
root.mainloop()

How can I pop up a messagebox from a menu?

I am a newbie in Python. I want to create a program with Tkinter that takes the entry from the entry "box" and then compares each character of it with the charset and finally pops up a messagebox that shows the phrase. I have almost complete it but I can not make this line work:
info_menu.add_command(label="About",
command=messagebox.showwarning(message="Creator: GakPower\nVersion: 1.0.0\nCreated at 1/5/2017")
Full code:
from tkinter import ttk
from tkinter import *
from tkinter import messagebox
import string as s
class Bruteforcer:
def output(self, result):
self.result = result
if result == "":
messagebox.showwarning(title="Enter a Phrase",
message="Please enter a Phrase!")
else:
messagebox.showinfo(title="Phrase Found!",
message=("The process completed Successfully!\n The Phrase Found!!!!\n", result))
def submit_button_pressed(self):
entry_val = self.entry_value.get()
charset = list(s.ascii_letters + "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψω" + s.digits + s.punctuation)
result = ""
x = 0
while x <= len(entry_val)-1:
echar = entry_val[x]
for char in charset:
if char == echar:
result += echar
x += 1
break
return self.output(result)
def __init__(self, root):
self.entry_value = StringVar(root, "")
self.the_menu = Menu(root)
info_menu = Menu(self.the_menu, tearoff=0)
**info_menu.add_command(label="About",
command=messagebox.showwarning(message="Creator: GakPower\nVersion: 1.0.0\nCreated at 1/5/2017")**
)
info_menu.add_separator()
info_menu.add_command(label="Quit", command=root.quit)
self.the_menu.add_cascade(label="Info", menu=info_menu)
root.config(menu=self.the_menu)
text_fond = StringVar()
text_fond.set("Times")
root.title("Graphical Bruteforcer")
root.geometry("500x500")
root.resizable(width=False, height=False)
style = ttk.Style()
style.configure("TButton",
foreground="red",
fond="Times 20",
padding=10)
style.configure("TEntry",
foreground="red",
fond="Times 20",
padding=10)
style.configure("TLabel",
foreground="red",
fond="Times 35 Bold")
# ---------- Entry -----------
self.entry_value = ttk.Entry(root,
textvariable=self.entry_value, width=25, state="normal")
self.entry_value.grid(row=1, columnspan=2)
# ---------- Label ----------
self.secret_label = ttk.Label(root,
text="The Secret Phrase").grid(row=0, column=0)
# ---------- Button ---------
self.button_submit = ttk.Button(root,
text="Submit", command=self.submit_button_pressed)
self.button_submit.grid(row=1, column=2)
root = Tk()
brute = Bruteforcer(root)
root.mainloop()
As furas said in the comments, command= expects a function. So you should replace
info_menu.add_command(label="About",
command=messagebox.showwarning(message="Creator: GakPower\nVersion: 1.0.0\nCreated at 1/5/2017"))
by something like
def show_about():
''' show the about messagebox '''
messagebox.showwarning(message="Creator: GakPower\nVersion: 1.0.0\nCreated at 1/5/2017")
info_menu.add_command(label="About", command=show_about)

Why don't any of my buttons work?

First i had the sqrt button which worked fine, and then I added the pi button, and nothing worked, i tried changing everything and i still don't know whats wrong! Please someone help.
import sys
from tkinter import *
from math import *
def sqrt_():
text = ment.get()
a = sqrt(text)
label['text'] = a
def pi_():
text = ment.get()
a = pi(text)
label_1['text'] = a
root = Tk()
root.title('Conversions')
root.geometry('400x400')
#Get square root
sqrt_button = Button(root, text='Get Square root',command= sqrt_).place(x='160', y='5')
label = Label(root, text='')
label.place(x=5, y=30)
ment = IntVar()
entry = Entry(textvariable=ment).place(x='5', y= '10 ')
#Get Pi
pi_button = Button(root, text='Get Pi',command= pi_).place(x='160', y='50')
label_1 = Label(root, text='')
label_1.place(x=55, y=200)
ment = IntVar()
entry_1 = Entry(textvariable=ment).place(x='5', y= '55 ')
root.mainloop()
First, you don't define the function pi which means when you click the second button it will fail.
Second, you redefined the ment. In this case both two entries will be bound to the same int. This means when you click the first button, it will read the value from the second entry. So change all the second ment to ment_1. The name, the name in entry and the name in pi_.
import sys
from tkinter import *
from math import *
def sqrt_():
text = ment.get()
a = sqrt(text)
label['text'] = a
def pi_():
label_1['text'] = pi
root = Tk()
root.title('Conversions')
root.geometry('400x400')
#Get square root
sqrt_button = Button(root, text='Get Square root',command= sqrt_).place(x='160', y='5')
label = Label(root, text='')
label.place(x=5, y=30)
ment = IntVar()
entry = Entry(textvariable=ment).place(x='5', y= '10 ')
#Get Pi
pi_button = Button(root, text='Get Pi',command= pi_).place(x='160', y='50')
label_1 = Label(root, text='')
label_1.place(x=55, y=200)
ment_1 = IntVar()
entry_1 = Entry(textvariable=ment_1).place(x='5', y= '55 ')
root.mainloop()
pi isn't a function it is a constant so:
def pi_():
label_1['text'] = pi

Categories

Resources