Tkinter: Adding a scrollbar to a canvas - python

I'm trying to add a scrollbar to my tkinter window which stays in place and scrolls through a frame. However, whenever I launch the application, the scrollbar is greyed out. Here is the relevant excerpt from my code:
self.bigFrame = ttk.Frame(self,width = 1080,height = 500)
self.hsb = tk.Scrollbar(self.bigFrame,orient = "horizontal")
self.hsb.pack(side = TOP, fill = X)
self.treeCanvas = tk.Canvas(self.bigFrame,width = 1080,height = 500,xscrollcommand = self.hsb.set)
self.treeFrame = tk.Frame(self.treeCanvas,width = 1080,height = 500)
self.treeCanvas.create_window((0,0),window=self.treeFrame,anchor = 'nw')
self.treeCanvas.config(scrollregion = self.treeCanvas.bbox("all"))
self.treeCanvas.pack(side = BOTTOM,fill = X)
self.treeFrame.pack(side = BOTTOM,fill = X)
self.hsb.config(command = self.treeCanvas.xview)
self.tree = ttk.Treeview(self.treeFrame,selectmode='browse',height = 100, columns = ('name','purchaseprice','previousprices','listingprice','buyingformat','postage','fees','potprofit','offers','viewcount','sold','offertaken','username','dispatch','delivered','returned','relist','feedback'))
self.tree.heading('#0',text = 'saleID',anchor = 'w')
self.tree.heading('name',text = "Item Name",anchor = 'w')
self.tree.heading('purchaseprice',text = "Purchase Price",anchor = 'w')
self.tree.heading('previousprices',text = "Previous Prices",anchor = 'w')
self.tree.heading('listingprice',text = "Listing Price", anchor = 'w')
self.tree.heading('buyingformat',text = "Buying Format",anchor = 'w')
self.tree.heading('postage',text = "Postage",anchor = 'w')
self.tree.heading('fees',text = "Fees",anchor = 'w')
self.tree.heading('potprofit',text = "Potential Profit",anchor = 'w')
self.tree.heading('offers',text = "Best Offer",anchor = 'w')
self.tree.heading('viewcount',text = "Viewcount",anchor = 'w')
self.tree.heading('sold',text = "Sold?",anchor = 'w')
self.tree.heading('offertaken',text = "Offer Taken?",anchor = 'w')
self.tree.heading('username',text = "Username",anchor = 'w')
self.tree.heading('dispatch',text = "Dispatched?",anchor = 'w')
self.tree.heading('delivered',text = "Delivered?",anchor = 'w')
self.tree.heading('returned',text = "Returned?",anchor = 'w')
self.tree.heading('relist',text = "Relisted?",anchor = 'w')
self.tree.heading('feedback',text = "Feedback",anchor = 'w')
self.tree.pack(side = BOTTOM, fill = X)
self.bigFrame.grid(row = 11,column = 0,columnspan = 100,pady=(5,0),sticky = 'nw')
self.bigFrame.grid_rowconfigure(0,weight = 1)
self.bigFrame.grid_columnconfigure(0,weight = 1)
self.bigFrame.grid_propagate(False)
I'm sure it's an issue with the ordering of lines, but none of the orders I've tried have worked.

The reason your scrollbar is greyed out is because you are missing this line:
self.treeFrame.update_idletasks()
Below implemented in the rest of your code.
...
self.treeCanvas.create_window((0,0),window=self.treeFrame,anchor = 'nw')
# add this
self.treeFrame.update_idletasks()
bbox = self.treeCanvas.bbox(tk.ALL)
# Update this
self.treeCanvas.config(scrollregion=bbox, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT)
self.treeCanvas.pack(side = BOTTOM,fill = X)
self.treeFrame.pack(side = BOTTOM,fill = X)
...
Hopefully this answer helps, if not you could try the last answer from this question, which helped me alot.

Related

'timestamp' messages appeared on my terminal, but i didn't code print('timestamp')

enter image description hereI made my autobot for coin trade.
I'm using iterm2 terminal to operate my code.
But there's some problem I don't understand.
first I use the same fuction by changing parameter, symbolname etc.
but on the terminal window for A coin, there's only 'timestamp' message.
i can't tell if it is error or not because there's no error message
and i didn't code print('timestamp')
on the other terminal windows for other coin, there's no such a message.
I guess my explanation is not enough.
but if you have any idea about this kind of situations, please tell me.
I'm using python.
thank you already!!
sometimes, although i didn't change anytihng.
'timestamp' message was disappeared.
enter image description here
enter code here
def runBot(symbol, second=int):
try:
subtitle = 'B'
fourth_interval = '30m'
symbol = symbol
path = path
df_1 = callChart(exchange=exchange, symbol=symbol, interval='15m')
df_2 = callChart(exchange=exchange, symbol=symbol, interval='5m')
df_3 = callChart(exchange=exchange, symbol=symbol, interval='1m')
df_4 = callChart(exchange=exchange, symbol=symbol, interval='30m')
df_5 = callChart(exchange=exchange, symbol=symbol, interval='1h')
df_6 = callChart(exchange=exchange, symbol=symbol, interval='4h')
df_7 = callChart(exchange=exchange, symbol=symbol, interval='2h')
n4hma2 = df_6.ma20[-1]
n4hma6 = df_6.ma60[-1]
n4hma8 = df_6.ma80[-1]
p4h_rsi = df_6.rsi[-2]
p4h_open = df_6.open[-2]
p4h_close = df_6.close[-2]
n1hma2 = df_5.ma20[-1]
n1hma6 = df_5.ma60[-1]
n1hma8 = df_5.ma80[-1]
n1h_low = df_5.low[-1]
n1h_high = df_5.high[-1]
n1h_open = df_5.open[-1]
p1h_rsi = df_5.rsi[-2]
p1hma2 = df_5.ma20[-2]
p1hma6 = df_5.ma60[-2]
p1hma8 = df_5.ma80[-2]
p1h_close = df_5.close[-2]
n30ma2 = df_4.ma20[-1]
n30ma6 = df_4.ma60[-1]
n30ma8 = df_4.ma80[-1]
n30_high = df_4.high[-1]
n30_low = df_4.low[-1]
n30_open = df_4.open[-1]
p30_rsi = df_4.rsi[-2]
p30_rsi = df_4.rsi[-2]
p30_close = df_4.close[-2]
pp30_close = df_4.close[-3]
ppp30_close = df_4.close[-4]
p30ma2 = df_4.ma20[-2]
p30ma6 = df_4.ma60[-2]
p30ma8 = df_4.ma80[-2]
pp30ma2 = df_4.ma20[-4]
pp30ma6 = df_4.ma60[-4]
pp30ma8 = df_4.ma80[-4]
ppp30ma2 = df_4.ma20[-4]
ppp30ma6 = df_4.ma60[-4]
ppp30ma8 = df_4.ma80[-4]
p4_30ma2 = df_4.ma20[-5]
p4_30ma6 = df_4.ma60[-5]
p4_30ma8 = df_4.ma80[-5]
n_price = df_1.close[-1]
n15ma2 = df_1.ma20[-1]
n15ma6 = df_1.ma60[-1]
n15ma8 = df_1.ma80[-1]
p15_close = df_1.close[-2]
p15_open = df_1.open[-2]
n15_high = df_1.high[-1]
n15_low = df_1.low[-1]
p15ma2 = df_1.ma20[-2]
p15ma6 = df_1.ma60[-2]
p15ma8 = df_1.ma80[-2]
n5ma2 = df_2.ma20[-1]
n5ma6 = df_2.ma60[-1]
n5ma8 = df_2.ma80[-1]
n5_high = df_2.high[-1]
n5_low = df_2.low[-1]
p5ma2 = df_2.ma20[-2]
p5ma6 = df_2.ma60[-2]
p5ma8 = df_2.ma80[-2]
p5_close = df_2.close[-2]
n1ma2 = df_3.ma20[-1]
n1ma6 = df_3.ma60[-1]
n1ma8 = df_3.ma80[-1]
p1m_close = df_3.close[-2]
p1ma2 = df_3.ma20[-2]
p1ma6 = df_3.ma60[-2]
p1ma8 = df_3.ma80[-2]
n2hma2 = df_7.ma20[-1]
n2hma6 = df_7.ma60[-1]
n2hma8 = df_7.ma80[-1]
now = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
now_date = datetime.date(now.year, now.month, now.day)
now_time = datetime.time(now.hour, now.minute, now.second)
what_day = now.weekday()
timestamp = time.mktime(datetime.datetime.strptime(str(f'{now_date} {now_time}'), '%Y-%m-%d %H:%M:%S').timetuple())
mt4 = datetime.datetime.utcnow() + datetime.timedelta(hours=3)
mt4_date = datetime.date(mt4.year, mt4.month, mt4.day)
mt4_time = datetime.time(mt4.hour, mt4.minute, mt4.second)
total_balance = exchange.fetch_balance()['USDT']['total']
total_balance2 = exchange2.fetch_balance()['USDT']['total']
total_balance5 = exchange5.fetch_balance()['USDT']['total']
print(colors.fg.blue, f'{subtitle}', colors.reset, colors.fg.green, f'{symbol}', colors.reset, f'{n_price}', colors.fg.yellow, f'{now_date} {now_time}', colors.reset)

python / I think It can write it briefly, but I don't know

This is the code I wrote.
Enter data of JSON into EXEL.
I tried .format() but failed.
I think it's too inefficient.
What should I do to make it simple?
Ask for help
DATA:
{"Y": ["1950","1951","1952","1953","1954","1955"],
"DATA":[
{"M":"1월",
"DATA1":164, "DATA2":173, "DATA3":2374,
"DATA4":183, "DATA5":186, "DATA6":2374,
"DATA7":151, "DATA8":145
},
{"M":"2월",
"DATA1":174, "DATA2":138, "DATA3":2374,
"DATA4":178, "DATA5":104, "DATA6":2374,
"DATA7":178, "DATA8":142
},
{"M":"3월",
"DATA1":135,"DATA2":173,"DATA3":2374,
"DATA4":104,"DATA5":176,"DATA6":2374,
"DATA7":134,"DATA8":178
},
{"M":"4월",
"DATA1":178,"DATA2":102,"DATA3":2374,
"DATA4":175,"DATA5":142,"DATA6":2374,
"DATA7":101,"DATA8":112
},
{"M":"5월",
"DATA1":135,"DATA2":168,"DATA3":2374,
"DATA4":127,"DATA5":104,"DATA6":2374,
"DATA7":167,"DATA8":183
},
{"M":"6월",
"DATA1":102,"DATA2":175,"DATA3":2374,
"DATA4":178,"DATA5":190,"DATA6":2374,
"DATA7":197,"DATA8":180},
{"M":"7월",
"DATA1":135,"DATA2":105,"DATA3":2374,
"DATA4":168,"DATA5":145,"DATA6":2374,
"DATA7":199,"DATA8":140},
{"M":"8월",
"DATA1":178,"DATA2":137,"DATA3":2374,
"DATA4":100,"DATA5":168,"DATA6":2374,
"DATA7":142,"DATA8":199
},
{"M":"9월",
"DATA1":135,"DATA2":175,"DATA3":2374,
"DATA4":135,"DATA5":124,"DATA6":2374,
"DATA7":176,"DATA8":125
},
{"M":"10월",
"DATA1":140,"DATA2":105,"DATA3":2374,
"DATA4":133,"DATA5":133,"DATA6":2374,
"DATA7":104,"DATA8":104
},
{"M":"11월",
"DATA1":199,"DATA2":178,"DATA3":2374,
"DATA4":170,"DATA5":157,"DATA6":2374,
"DATA7":178,"DATA8":167
},
{"M":"12월",
"DATA1":138,"DATA2":196,"DATA3":2374,
"DATA4":109,"DATA5":107,"DATA6":2374,
"DATA7":100,"DATA8":104
}
],
"단위":"건","오차":"5%"
}
CODE:
import json
from openpyxl import Workbook
wb = Workbook()
wb.save('test1.xlsx')
sheet1 = wb.active
sheet1.title = 'abcd'
with open('getdata.JSON', encoding='UTF8') as resp:
project_info = json.load(resp)
sheet1['B10'] = project_info['Y'][0]
sheet1['C10'] = project_info['Y'][1]
sheet1['D10'] = project_info['Y'][2]
sheet1['E10'] = project_info['Y'][3]
sheet1['F10'] = project_info['Y'][4]
sheet1['G10'] = project_info['Y'][5]
sheet1['A11'] = project_info['DATA'][0].get('M')
sheet1['A12'] = project_info['DATA'][1].get('M')
sheet1['A13'] = project_info['DATA'][2].get('M')
sheet1['A14'] = project_info['DATA'][3].get('M')
sheet1['A15'] = project_info['DATA'][4].get('M')
sheet1['A16'] = project_info['DATA'][5].get('M')
sheet1['A17'] = project_info['DATA'][6].get('M')
sheet1['A18'] = project_info['DATA'][7].get('M')
sheet1['A19'] = project_info['DATA'][8].get('M')
sheet1['A20'] = project_info['DATA'][9].get('M')
sheet1['A21'] = project_info['DATA'][10].get('M')
sheet1['A22'] = project_info['DATA'][11].get('M')
sheet1['B11'] = project_info['DATA'][0].get('DATA1')
sheet1['B12'] = project_info['DATA'][1].get('DATA1')
sheet1['B13'] = project_info['DATA'][2].get('DATA1')
sheet1['B14'] = project_info['DATA'][3].get('DATA1')
sheet1['B15'] = project_info['DATA'][4].get('DATA1')
sheet1['B16'] = project_info['DATA'][5].get('DATA1')
sheet1['B17'] = project_info['DATA'][6].get('DATA1')
sheet1['B18'] = project_info['DATA'][7].get('DATA1')
sheet1['B19'] = project_info['DATA'][8].get('DATA1')
sheet1['B20'] = project_info['DATA'][9].get('DATA1')
sheet1['B21'] = project_info['DATA'][10].get('DATA1')
sheet1['B22'] = project_info['DATA'][11].get('DATA1')
sheet1['C11'] = project_info['DATA'][0].get('DATA2')
sheet1['C12'] = project_info['DATA'][1].get('DATA2')
sheet1['C13'] = project_info['DATA'][2].get('DATA2')
sheet1['C14'] = project_info['DATA'][3].get('DATA2')
sheet1['C15'] = project_info['DATA'][4].get('DATA2')
sheet1['C16'] = project_info['DATA'][5].get('DATA2')
sheet1['C17'] = project_info['DATA'][6].get('DATA2')
sheet1['C18'] = project_info['DATA'][7].get('DATA2')
sheet1['C19'] = project_info['DATA'][8].get('DATA2')
sheet1['C20'] = project_info['DATA'][9].get('DATA2')
sheet1['C21'] = project_info['DATA'][10].get('DATA2')
sheet1['C22'] = project_info['DATA'][11].get('DATA2')
sheet1['D11'] = project_info['DATA'][0].get('DATA4')
sheet1['D12'] = project_info['DATA'][1].get('DATA4')
sheet1['D13'] = project_info['DATA'][2].get('DATA4')
sheet1['D14'] = project_info['DATA'][3].get('DATA4')
sheet1['D15'] = project_info['DATA'][4].get('DATA4')
sheet1['D16'] = project_info['DATA'][5].get('DATA4')
sheet1['D17'] = project_info['DATA'][6].get('DATA4')
sheet1['D18'] = project_info['DATA'][7].get('DATA4')
sheet1['D19'] = project_info['DATA'][8].get('DATA4')
sheet1['D20'] = project_info['DATA'][9].get('DATA4')
sheet1['D21'] = project_info['DATA'][10].get('DATA4')
sheet1['D22'] = project_info['DATA'][11].get('DATA4')
sheet1['E11'] = project_info['DATA'][0].get('DATA5')
sheet1['E12'] = project_info['DATA'][1].get('DATA5')
sheet1['E13'] = project_info['DATA'][2].get('DATA5')
sheet1['E14'] = project_info['DATA'][3].get('DATA5')
sheet1['E15'] = project_info['DATA'][4].get('DATA5')
sheet1['E16'] = project_info['DATA'][5].get('DATA5')
sheet1['E17'] = project_info['DATA'][6].get('DATA5')
sheet1['E18'] = project_info['DATA'][7].get('DATA5')
sheet1['E19'] = project_info['DATA'][8].get('DATA5')
sheet1['E20'] = project_info['DATA'][9].get('DATA5')
sheet1['E21'] = project_info['DATA'][10].get('DATA5')
sheet1['E22'] = project_info['DATA'][11].get('DATA5')
sheet1['F11'] = project_info['DATA'][0].get('DATA7')
sheet1['F12'] = project_info['DATA'][1].get('DATA7')
sheet1['F13'] = project_info['DATA'][2].get('DATA7')
sheet1['F14'] = project_info['DATA'][3].get('DATA7')
sheet1['F15'] = project_info['DATA'][4].get('DATA7')
sheet1['F16'] = project_info['DATA'][5].get('DATA7')
sheet1['F17'] = project_info['DATA'][6].get('DATA7')
sheet1['F18'] = project_info['DATA'][7].get('DATA7')
sheet1['F19'] = project_info['DATA'][8].get('DATA7')
sheet1['F20'] = project_info['DATA'][9].get('DATA7')
sheet1['F21'] = project_info['DATA'][10].get('DATA7')
sheet1['F22'] = project_info['DATA'][11].get('DATA7')
sheet1['G11'] = project_info['DATA'][0].get('DATA8')
sheet1['G12'] = project_info['DATA'][1].get('DATA8')
sheet1['G13'] = project_info['DATA'][2].get('DATA8')
sheet1['G14'] = project_info['DATA'][3].get('DATA8')
sheet1['G15'] = project_info['DATA'][4].get('DATA8')
sheet1['G16'] = project_info['DATA'][5].get('DATA8')
sheet1['G17'] = project_info['DATA'][6].get('DATA8')
sheet1['G18'] = project_info['DATA'][7].get('DATA8')
sheet1['G19'] = project_info['DATA'][8].get('DATA8')
sheet1['G20'] = project_info['DATA'][9].get('DATA8')
sheet1['G21'] = project_info['DATA'][10].get('DATA8')
sheet1['G22'] = project_info['DATA'][11].get('DATA8')
wb.save('test1.xlsx')
sheet = ['B10', 'C10', 'D10', 'E10', 'F10', 'G10']
for i in range(0,5,1):
sheet1[sheet[i]] = project_info['Y'][i]
_dict = {"A":"M", "B":"DATA1", "C":"DATA2", "D":"DATA4", "E":"DATA5", "F":"DATA7", "G":"DATA8" }
for k, v in _dict.items():
for i in range(0, 11, 1):
key = k + str(i+11)
sheet1[key] = project_info['DATA'][i].get(v)
You should be able to use a nested loop over your letters
This will loop over the letters b to g (indexes 1 to 7 of the alphabet, adjust as required) and then creating 12 entries per letter
import string
for idx, letter in enumerate(string.ascii_lowercase[1:7]):
for i in range(12):
sheet1[f'{letter}{i+11}'] = project_info['DATA'][i].get(f'DATA{idx + 1}')
(Written on a phone, apologies for formatting)
You can use similar loops for the a column and y info

Why is Flopy giving the same results?

I tried to use flopy, so I could try running some optimization procedures with python and modflow. Modflow requires a number of data to work with and we provide that info using different files.
We provide the input and flopy runs modflow
My trouble is that, flopy seems to disregard the input files and gives the same result, no matter what input I give.
Here's the code:
nper = 10
class BASreader:
def __init__(self):
self.ibound = None
self.head = None
with open("inps/bas/ibound", "r") as f:
data = f.read().replace("-", " -").split()
data = [int(x) for x in data]
data = np.array(data).reshape(1, 71, 24)
self.ibound = data
with open("inps/bas/head", "r") as f:
data = f.read().split()
data = [float(x) for x in data]
self.head = np.array(data).reshape(1, 71, 24)
class Modflow:
def __init__(self):
self.modelname = 'outs/gen1'
self.mf = flopy.modflow.Modflow(self.modelname, exe_name=r'G:\Program Files (x86)\Visual MODFLOW\mf2005.exe')
dis = flopy.modflow.ModflowDis.load("inps/yo.dis", self.mf)
basreader = BASreader()
bas = flopy.modflow.ModflowBas(self.mf, ibound=basreader.ibound, strt=basreader.head)
self.prev_headdata = basreader.head
wel = flopy.modflow.ModflowWel(self.mf, stress_period_data=WellProvider(nper).wells)
fname = 'inps/yo.evt'
fhandle = open(fname, 'r')
packages = []
ext_unit_dict = {22: flopy.utils.mfreadnam.NamData('EVT', fname, fhandle, packages)}
evt = flopy.modflow.ModflowEvt.load(fhandle, self.mf, ext_unit_dict=ext_unit_dict)
fhandle.close()
rech = {}
for x in range(nper):
rech[x] = 1.44e-5
rch = flopy.modflow.ModflowRch(self.mf, rech=rech)
stress_period_data = {}
for kper in range(nper):
for kstp in range(int(nper/10)):
stress_period_data[(kper, kstp)] = ['save head',
'save drawdown',
'save budget',
'print head',
'print drawdown',
'print budget']
oc = flopy.modflow.ModflowOc(self.mf, stress_period_data=stress_period_data, compact=True)
chd = flopy.modflow.ModflowChd.load("inps/yo.chd", self.mf)
lpf = flopy.modflow.ModflowLpf(self.mf, hk=14.44, vka=14.44, ipakcb=53, sy=0.22)
self.mf.write_input()
def run(self):
success, buff = self.mf.run_model(silent=True)
headobj = bf.HeadFile(self.modelname + '.hds')
newheaddata = headobj.get_alldata()[-1][0]
return newheaddata
mdflw = Modflow()
mdflw.run()
Now, even if I change the EVT, RCH or WEL info, the results are same.
I even tried to not include the above files, still the results were same.
Any pointers?
This revision of your script results in different head results (since different groundwater recharge values are used). I used the bcf2ss MODFLOW-2005 input files as base files in the revised example.
Not entirely sure why your script wasn't working since your input files weren't available.
import os
import numpy as np
import flopy
class BASreader:
def __init__(self):
self.ibound = None
self.head = None
with open("inps/bas/ibound", "r") as f:
data = f.read().replace("-", " -").split()
data = [int(x) for x in data]
data = np.array(data).reshape(2, 10, 15)
self.ibound = data
with open("inps/bas/head", "r") as f:
data = f.read().split()
data = [float(x) for x in data]
self.head = np.array(data).reshape(2, 10, 15)
class Modflow:
def __init__(self, ws='outs', rech_val=.0040, wel_data=None):
self.model_ws = ws
self.modelname = 'gen1'
self.mf = flopy.modflow.Modflow(self.modelname, exe_name='mf2005',
model_ws=self.model_ws)
dis = flopy.modflow.ModflowDis.load("inps/yo.dis", self.mf, check=False)
nper = dis.nper
nstp = dis.nstp.array
basreader = BASreader()
bas = flopy.modflow.ModflowBas(self.mf, ibound=basreader.ibound,
strt=basreader.head)
self.prev_headdata = basreader.head
bcf = flopy.modflow.ModflowBcf.load("inps/yo.bc6", self.mf)
if wel_data is None:
wel_data = [[1, 2, 3, -35000.],
[1, 7, 3, -35000.]]
wel_spd = {1: wel_data}
wel = flopy.modflow.ModflowWel(self.mf,
stress_period_data=wel_spd)
riv = flopy.modflow.ModflowRiv.load('inps/yo.riv', self.mf, check=False)
rech = {}
for x in range(nper):
rech[x] = rech_val
rch = flopy.modflow.ModflowRch(self.mf, rech=rech)
pcg = flopy.modflow.ModflowPcg.load('inps/yo.pcg', self.mf)
stress_period_data = {}
for kper in range(nper):
for kstp in range(nstp[kper]):
stress_period_data[(kper, kstp)] = ['save head',
'save drawdown',
'save budget',
'print head',
'print drawdown',
'print budget']
oc = flopy.modflow.ModflowOc(self.mf,
stress_period_data=stress_period_data,
compact=True)
self.mf.write_input()
def run(self):
success, buff = self.mf.run_model(silent=True)
fpth = os.path.join(self.model_ws, self.modelname + '.hds')
headobj = flopy.utils.HeadFile(fpth)
newheaddata = headobj.get_data(idx=1)
return newheaddata
if __name__ == "__main__":
m1 = Modflow()
h1 = m1.run()
m2 = Modflow(rech_val=.0041)
h2 = m2.run()
assert np.array_equal(h1, h2), 'h1 does not equal h2'

If / else statement not working depending on random number (Python)

I'm making a text encrypt-er that randomizes the pattern of symbols used (abcd) but after the first if statement, the program no longer works. New, old, get , and tag are the 4 letter to symbol translations. I tested out only the first if statement by itself and it worked perfectly fine. Also any tips in how to shorten the code would be much appreciated.
our_str = input("Mornin' ")
length = (len(our_str)/2)
rounded = round(length)
import random
rand = random.randint(1,6)
print(rand)
if rand <= 2: #abcd
new_str = our_str[:rounded].replace('a', ']')
new1_str = new_str.replace('b', '◙')
new2_str = new1_str.replace('c', '♂')
new3_str = new2_str.replace('d', 'd')
new4_str = new3_str.replace('e', 'e')
new5_str = new4_str.replace('f', '▓')
new6_str = new5_str.replace('g', '─')
new7_str = new6_str.replace('h', 'Φ')
new8_str = new7_str.replace('i', 'Θ')
new9_str = new8_str.replace('j', '≥')
new10_str = new9_str.replace('k', '≤')
new11_str = new10_str.replace('l', 'L')
new12_str = new11_str.replace('m', 'M')
new13_str = new12_str.replace('n', 'V')
new14_str = new13_str.replace('o', 'W')
new15_str = new14_str.replace('p', '►')
new16_str = new15_str.replace('q', '◄')
new17_str = new16_str.replace('r', '→')
new18_str = new17_str.replace('s', '←')
new19_str = new18_str.replace('t', 't')
new20_str = new19_str.replace('u', 'u')
new21_str = new20_str.replace('v', '~')
new22_str = new21_str.replace('w', '⌂')
new23_str = new22_str.replace('x', '°')
new24_str = new23_str.replace('y', '∙')
new25_str = new24_str.replace('z', '☻')
new26_str = new25_str.replace(' ', 'f')
old_str = our_str[rounded:2 * rounded].replace('a', 'Y')
old1_str = old_str.replace('b', 'É')
old2_str = old1_str.replace('c', 'Θ')
old3_str = old2_str.replace('d', '╩')
old4_str = old3_str.replace('e', 'b')
old5_str = old4_str.replace('f', '█')
old6_str = old5_str.replace('g', '=')
old7_str = old6_str.replace('h', '↑')
old8_str = old7_str.replace('i', 'U')
old9_str = old8_str.replace('j', '⌂')
old10_str = old9_str.replace('k', '┬')
old11_str = old10_str.replace('l', 'æ')
old12_str = old11_str.replace('m', '◄')
old13_str = old12_str.replace('n', '1')
old14_str = old13_str.replace('o', 'B')
old15_str = old14_str.replace('p', 'Ñ')
old16_str = old15_str.replace('q', '╡')
old17_str = old16_str.replace('r', '▌')
old18_str = old17_str.replace('s', '♣')
old19_str = old18_str.replace('t', 'Γ')
old20_str = old19_str.replace('u', 'τ')
old21_str = old20_str.replace('v', '╔')
old22_str = old21_str.replace('w', '░')
old23_str = old22_str.replace('x', '┘')
old24_str = old23_str.replace('y', 'ó')
old25_str = old24_str.replace('z', ';')
old26_str = old25_str.replace(' ', 'ß')
get_str = our_str[2 * rounded:3 * rounded].replace('a', 'ç')
get1_str = get_str.replace('b', '1')
get2_str = get1_str.replace('c', '♣')
get3_str = get2_str.replace('d', 'ⁿ')
get4_str = get3_str.replace('e', '♠')
get5_str = get4_str.replace('f', 'S')
get6_str = get5_str.replace('g', '°')
get7_str = get6_str.replace('h', '♫')
get8_str = get7_str.replace('i', 'D')
get9_str = get8_str.replace('j', '│')
get10_str = get9_str.replace('k', '←')
get11_str = get10_str.replace('l', 'ƒ')
get12_str = get11_str.replace('m', 'Æ')
get13_str = get12_str.replace('n', 'P')
get14_str = get13_str.replace('o', '#') #skipped 0781, 6406
get15_str = get14_str.replace('p', '.') #0899
get16_str = get15_str.replace('q', '┤') #0348
get17_str = get16_str.replace('r', 'µ')
get18_str = get17_str.replace('s', 'E')
get19_str = get19_str.replace('t', '§')
get20_str = get20_str.replace('u', '▬')
get21_str = get21_str.replace('v', 'û')
get22_str = get22_str.replace('w', '♀')
get23_str = get23_str.replace('x', '&')
get24_str = get24_str.replace('y', '≈')
get25_str = get25_str.replace('z', 'ª') #4460
get26_str = get26_str.replace(' ', 'N')
tag_str = our_str[3 * rounded:].replace('a', '╬')
tag1_str = tag_str.replace('b', '↓')
tag2_str = tag1_str.replace('c', '<')
tag3_str = tag2_str.replace('d', '╦')
tag4_str = tag3_str.replace('e', '-')
tag5_str = tag4_str.replace('f', 'δ') #skipped 360
tag6_str = tag5_str.replace('g', '▼')
tag7_str = tag6_str.replace('h', '╫')
tag8_str = tag7_str.replace('i', '`')
tag9_str = tag8_str.replace('j', 'û')
tag10_str = tag9_str.replace('k', '±')
tag11_str = tag10_str.replace('l', '⌡')
tag12_str = tag11_str.replace('m', '≈')
tag13_str = tag12_str.replace('n', ']')
tag14_str = tag13_str.replace('o', '╗')
tag15_str = tag14_str.replace('p', '┐')
tag16_str = tag15_str.replace('q', '>')
tag17_str = tag16_str.replace('r', '╞')
tag18_str = tag17_str.replace('s', '╟') #627
tag19_str = tag18_str.replace('t', '╘')
tag20_str = tag19_str.replace('u', 'L')
tag21_str = tag20_str.replace('v', 'v') #353
tag22_str = tag21_str.replace('w', '#')
tag23_str = tag22_str.replace('x', 'R')
tag24_str = tag23_str.replace('y', ';')
tag25_str = tag24_str.replace('z', '~')
tag26_str = tag25_str.replace(' ', '▓')
print(new26_str + old26_str + get26_str + tag26_str)
elif 2 < rand <= 4 #abdc
new_str = our_str[:rounded].replace('a', ']')
new1_str = new_str.replace('b', '◙')
new2_str = new1_str.replace('c', '♂')
new3_str = new2_str.replace('d', 'd')
new4_str = new3_str.replace('e', 'e')
new5_str = new4_str.replace('f', '▓')
new6_str = new5_str.replace('g', '─')
new7_str = new6_str.replace('h', 'Φ')
new8_str = new7_str.replace('i', 'Θ')
new9_str = new8_str.replace('j', '≥')
new10_str = new9_str.replace('k', '≤')
new11_str = new10_str.replace('l', 'L')
new12_str = new11_str.replace('m', 'M')
new13_str = new12_str.replace('n', 'V')
new14_str = new13_str.replace('o', 'W')
new15_str = new14_str.replace('p', '►')
new16_str = new15_str.replace('q', '◄')
new17_str = new16_str.replace('r', '→')
new18_str = new17_str.replace('s', '←')
new19_str = new18_str.replace('t', 't')
new20_str = new19_str.replace('u', 'u')
new21_str = new20_str.replace('v', '~')
new22_str = new21_str.replace('w', '⌂')
new23_str = new22_str.replace('x', '°')
new24_str = new23_str.replace('y', '∙')
new25_str = new24_str.replace('z', '☻')
new26_str = new25_str.replace(' ', 'f')
old_str = our_str[rounded:2 * rounded].replace('a', 'Y')
old1_str = old_str.replace('b', 'É')
old2_str = old1_str.replace('c', 'Θ')
old3_str = old2_str.replace('d', '╩')
old4_str = old3_str.replace('e', 'b')
old5_str = old4_str.replace('f', '█')
old6_str = old5_str.replace('g', '=')
old7_str = old6_str.replace('h', '↑')
old8_str = old7_str.replace('i', 'U')
old9_str = old8_str.replace('j', '⌂')
old10_str = old9_str.replace('k', '┬')
old11_str = old10_str.replace('l', 'æ')
old12_str = old11_str.replace('m', '◄')
old13_str = old12_str.replace('n', '1')
old14_str = old13_str.replace('o', 'B')
old15_str = old14_str.replace('p', 'Ñ')
old16_str = old15_str.replace('q', '╡')
old17_str = old16_str.replace('r', '▌')
old18_str = old17_str.replace('s', '♣')
old19_str = old18_str.replace('t', 'Γ')
old20_str = old19_str.replace('u', 'τ')
old21_str = old20_str.replace('v', '╔')
old22_str = old21_str.replace('w', '░')
old23_str = old22_str.replace('x', '┘')
old24_str = old23_str.replace('y', 'ó')
old25_str = old24_str.replace('z', ';')
old26_str = old25_str.replace(' ', 'ß')
get_str = our_str[3 * rounded:].replace('a', 'ç')
get1_str = get_str.replace('b', '1')
get2_str = get1_str.replace('c', '♣')
get3_str = get2_str.replace('d', 'ⁿ')
get4_str = get3_str.replace('e', '♠')
get5_str = get4_str.replace('f', 'S')
get6_str = get5_str.replace('g', '°')
get7_str = get6_str.replace('h', '♫')
get8_str = get7_str.replace('i', 'D')
get9_str = get8_str.replace('j', '│')
get10_str = get9_str.replace('k', '←')
get11_str = get10_str.replace('l', 'ƒ')
get12_str = get11_str.replace('m', 'Æ')
get13_str = get12_str.replace('n', 'P')
get14_str = get13_str.replace('o', '#') #skipped 0781, 6406
get15_str = get14_str.replace('p', '.') #0899
get16_str = get15_str.replace('q', '┤') #0348
get17_str = get16_str.replace('r', 'µ')
get18_str = get17_str.replace('s', 'E')
get19_str = get19_str.replace('t', '§')
get20_str = get20_str.replace('u', '▬')
get21_str = get21_str.replace('v', 'û')
get22_str = get22_str.replace('w', '♀')
get23_str = get23_str.replace('x', '&')
get24_str = get24_str.replace('y', '≈')
get25_str = get25_str.replace('z', 'ª') #4460
get26_str = get26_str.replace(' ', 'N')
tag_str = our_str[2 * rounded: 3 * rounded].replace('a', '╬')
tag1_str = tag_str.replace('b', '↓')
tag2_str = tag1_str.replace('c', '<')
tag3_str = tag2_str.replace('d', '╦')
tag4_str = tag3_str.replace('e', '-')
tag5_str = tag4_str.replace('f', 'δ') #skipped 360
tag6_str = tag5_str.replace('g', '▼')
tag7_str = tag6_str.replace('h', '╫')
tag8_str = tag7_str.replace('i', '`')
tag9_str = tag8_str.replace('j', 'û')
tag10_str = tag9_str.replace('k', '±')
tag11_str = tag10_str.replace('l', '⌡')
tag12_str = tag11_str.replace('m', '≈')
tag13_str = tag12_str.replace('n', ']')
tag14_str = tag13_str.replace('o', '╗')
tag15_str = tag14_str.replace('p', '┐')
tag16_str = tag15_str.replace('q', '>')
tag17_str = tag16_str.replace('r', '╞')
tag18_str = tag17_str.replace('s', '╟') #627
tag19_str = tag18_str.replace('t', '╘')
tag20_str = tag19_str.replace('u', 'L')
tag21_str = tag20_str.replace('v', 'v') #353
tag22_str = tag21_str.replace('w', '#')
tag23_str = tag22_str.replace('x', 'R')
tag24_str = tag23_str.replace('y', ';')
tag25_str = tag24_str.replace('z', '~')
tag26_str = tag25_str.replace(' ', '▓')
print(new26_str + old26_str + tag26_str + get26_str)
hi = input("Bye")
P.S - The hi input is to not let the Python console close.
1st Error: You have used variables in following statements without initializing them first
get19_str = get19_str.replace('t', '§')
get20_str = get20_str.replace('u', '▬')
get21_str = get21_str.replace('v', 'û')
get22_str = get22_str.replace('w', '♀')
get23_str = get23_str.replace('x', '&')
get24_str = get24_str.replace('y', '≈')
get25_str = get25_str.replace('z', 'ª') #4460
get26_str = get26_str.replace(' ', 'N')
2nd Error: If statements do not allow two relational operations to be performed on a single variable without using a logical operator for joining the two (in case of n relational operations you should use n-1 logical operators to combine them all)
Eg. Check if integer a is greater than 2 and less than 5
if (a>2) and (a<5):
#statements
So you will have to change your elif statement by seperating the two re
Try this:
elif ((rand > 2) and (rand <= 4)):
# Do your stuff here
Doing what you did will compare 2 to the expression (rand <= 4), which compares to a boolean, or 0/1.
The very first line: our_str = input("Mornin' ")
our_str should be converted to integer.
Your conditionals are not right.
elif 2 < rand <= 4: it doesn't work this way.
instead use elif rand in [3,4]: or elif rand > 2 and rand <= 4:
There are other errors as well, you can check the console and remove all the errors.
like you are using get19_str without even initialising it and so on...

Weird python/tkinter error

So I have this code:
from urllib2 import *
import re
import tkSimpleDialog
import os
import glob
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
image1 = PhotoImage(file="picture.gif")
w = image1.width()
h = image1.height()
master.geometry("%dx%d+0+0" % (w, h))
# tk.Frame has no image argument
panel1 = Label(master, image=image1)
panel1.pack(side='top', fill='both', expand='yes')
panel1.image = image1
self.e = Entry(frame)
self.e.grid(row=0, column=0)
b = Button(frame, text='Search', command=self.whale)
b.grid(row=0, column=1)
###
def whale(self):
page = '1'
def newre():
page = '1'
pages = int(page)
peg = pages + 1
pege = str(peg)
page = pege
self.whale()
alist = []
mu = self.e.get()
print mu
mus = mu.replace(' ','-')
op = urlopen('http://website' + mus + '-'+page+'.html')
ops = op.read()
if 'charset="utf-8">var playlist' in ops:
print 'yes'
cal = ops.split('charset="utf-8">var playlist',1)
del cal[0]
cv = str(cal)
cals = cv.split('},];</script><div',1)
del cals[1]
cals = str(cals)
v = cals.replace('{', '''
''')
vn = v.replace('[','')
vnm = vn.replace(']','')
parsed = re.findall('author : "([^"]+)",title : "([^"]+)",type : "([^"]+)",file : "([^"]+)",id : "([^"]+)', vnm)
print mus
cvb0 = ','.join(map(''.join,parsed[0]))
cvb1 = ','.join(map(''.join,parsed[1]))
cvb2 = ','.join(map(''.join,parsed[2]))
cvb3 = ','.join(map(''.join,parsed[3]))
cvb4 = ','.join(map(''.join,parsed[4]))
cvb5 = ','.join(map(''.join,parsed[5]))
cvb6 = ','.join(map(''.join,parsed[6]))
cvb7 = ','.join(map(''.join,parsed[7]))
cvb8 = ','.join(map(''.join,parsed[8]))
cvb9 = ','.join(map(''.join,parsed[9]))
canada0 = cvb0.split('sound,',1)
canada1 = cvb1.split('sound,',1)
canada2 = cvb2.split('sound,',1)
canada3 = cvb3.split('sound,',1)
canada4 = cvb4.split('sound,',1)
canada5 = cvb5.split('sound,',1)
canada6 = cvb6.split('sound,',1)
canada7 = cvb7.split('sound,',1)
canada8 = cvb8.split('sound,',1)
canada9 = cvb9.split('sound,',1)
song0 = canada0[0]
song1 = canada1[0]
song2 = canada2[0]
song3 = canada3[0]
song4 = canada4[0]
song5 = canada5[0]
song6 = canada6[0]
song7 = canada7[0]
song8 = canada8[0]
song9 = canada9[0]
del canada0[0]
del canada1[0]
del canada2[0]
del canada3[0]
del canada4[0]
del canada5[0]
del canada6[0]
del canada7[0]
del canada8[0]
del canada9[0]
run0 = str(canada0)
run1 = str(canada1)
run2 = str(canada2)
run3 = str(canada3)
run4 = str(canada4)
run5 = str(canada5)
run6 = str(canada6)
run7 = str(canada7)
run8 = str(canada8)
run9 = str(canada9)
#run0
runs0 = str(run0)
nun0 = runs0.split(',',1)
del nun0[1]
nun0 = str(nun0)
run0 = nun0.replace('[','')
runs0 = run0.replace(']','')
runss0 = runs0.replace('"','')
runsss0 = runss0.replace("'",'')
#run1
runs1 = str(run1)
nun1 = runs1.split(',',1)
del nun1[1]
nun1 = str(nun1)
run1 = nun1.replace('[','')
runs1 = run1.replace(']','')
runss1 = runs1.replace('"','')
runsss1 = runss1.replace("'",'')
#run2
runs2 = str(run2)
nun2 = runs2.split(',',1)
del nun2[1]
nun2 = str(nun2)
run2 = nun2.replace('[','')
runs2 = run2.replace(']','')
runss2 = runs2.replace('"','')
runsss2 = runss2.replace("'",'')
#run3
runs3 = str(run3)
nun3 = runs3.split(',',1)
del nun3[1]
nun3 = str(nun3)
run3 = nun3.replace('[','')
runs3 = run3.replace(']','')
runss3 = runs3.replace('"','')
runsss3 = runss3.replace("'",'')
#run4
runs4 = str(run4)
nun4 = runs4.split(',',1)
del nun4[1]
nun4 = str(nun4)
run4 = nun4.replace('[','')
runs4 = run4.replace(']','')
runss4 = runs4.replace('"','')
runsss4 = runss4.replace("'",'')
#run5
runs5 = str(run5)
nun5 = runs5.split(',',1)
del nun5[1]
nun5 = str(nun5)
run5 = nun5.replace('[','')
runs5 = run5.replace(']','')
runss5 = runs5.replace('"','')
runsss5 = runss5.replace("'",'')
#run6
runs6 = str(run6)
nun6 = runs6.split(',',1)
del nun6[1]
nun6 = str(nun6)
run6 = nun6.replace('[','')
runs6 = run6.replace(']','')
runss6 = runs6.replace('"','')
runsss6 = runss6.replace("'",'')
#run7
runs7 = str(run7)
nun7 = runs7.split(',',1)
del nun7[1]
nun7 = str(nun7)
run7 = nun7.replace('[','')
runs7 = run7.replace(']','')
runss7 = runs7.replace('"','')
runsss7 = runss7.replace("'",'')
#run8
runs8 = str(run8)
nun8 = runs8.split(',',1)
del nun8[1]
nun8 = str(nun8)
run8 = nun8.replace('[','')
runs8 = run8.replace(']','')
runss8 = runs8.replace('"','')
runsss8 = runss8.replace("'",'')
#run9
runs9 = str(run9)
nun9 = runs9.split(',',1)
del nun9[1]
nun9 = str(nun9)
run9 = nun9.replace('[','')
runs9 = run9.replace(']','')
runss9 = runs9.replace('"','')
runsss9 = runss9.replace("'",'')
def download0():
print 'downloading...'
url = runsss0
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song0 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download1():
print 'downloading...'
url = runsss1
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song1 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download2():
print 'downloading...'
url = runsss2
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song2 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download3():
print 'downloading...'
url = runsss3
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song3 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download4():
print 'downloading...'
url = runsss4
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song4 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download5():
print 'downloading...'
url = runsss5
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song5 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download6():
print 'downloading...'
url = runsss6
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song6 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download7():
print 'downloading...'
url = runsss7
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song7 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download8():
print 'downloading...'
url = runsss8
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song8 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download9():
print 'downloading...'
url = runsss9
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song9 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def replay():
Admin.destroy()
os.system('WhaleWire.py')
def library():
path = 'C:\Users\Psao\Desktop\whalewhire\Downloaded'
aw=[]
for infile in glob.glob( os.path.join(path,'*.mp3') ):
libr = infile.split('Downloaded',1)
aw.append('\n')
aw.append(infile)
la = Label(Admin,width=100,height=50, text=aw).grid(row=0,column=7)
b2s = Button(Admin,text='Search', command=replay).grid(row=0,column=8)
print song1
Label(Admin, text=song0).grid(row=1)
Label(Admin, text=song1).grid(row=2)
Label(Admin, text=song2).grid(row=3)
Label(Admin, text=song3).grid(row=4)
Label(Admin, text=song4).grid(row=5)
Label(Admin, text=song5).grid(row=6)
Label(Admin, text=song6).grid(row=7)
Label(Admin, text=song7).grid(row=8)
Label(Admin, text=song8).grid(row=9)
Label(Admin, text=song9).grid(row=10)
b0 = Button(Admin, text='Download', command=download0)
b1 = Button(Admin, text='Download', command=download1)
b2 = Button(Admin, text='Download', command=download2)
b3 = Button(Admin, text='Download', command=download3)
b4 = Button(Admin, text='Download', command=download4)
b5 = Button(Admin, text='Download', command=download5)
b6 = Button(Admin, text='Download', command=download6)
b7 = Button(Admin, text='Download', command=download7)
b8 = Button(Admin, text='Download', command=download8)
b9 = Button(Admin, text='Download', command=download9)
b10 = Button(Admin, text='More results', command=newre)
b11 = Button(Admin, text='Library', command=library)
b0.grid(row=1, column=1)
b1.grid(row=2, column=1)
b2.grid(row=3, column=1)
b3.grid(row=4, column=1)
b4.grid(row=5, column=1)
b5.grid(row=6, column=1)
b6.grid(row=7, column=1)
b7.grid(row=8, column=1)
b8.grid(row=9, column=1)
b9.grid(row=10, column=1)
b10.grid(row=10, column=2)
b11.grid(row=11, column=3)
Admin = Tk()
Admin.title('WhaleWires')
app = App(Admin)
Admin.mainloop()
I know it's really long and really repetitive, but i don't want to take the time to find a clean code for each thing.
Any way when I type in a song under two words it give me an error that vary of
an Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Users\Psao\Desktop\whalewhire\WhaleWire.py", line 93, in whale
cvb7 = ','.join(map(''.join,parsed[7]))
IndexError: list index out of range
but the parse[#] is somtimes diffrent
any help and also if you know any code that would shorten my code I would be greatful.
it seems that parsed is some times shorter than 10 items
the 0-9 variables should be in a list rather than as individual variables this would allow one to use a loop to repeat the same actions on the values rather than duplicating the code for each variable

Categories

Resources